mirror of
https://github.com/Azure/k8s-deploy.git
synced 2026-06-21 10:39:26 +08:00
Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9860cfe0c2 | |||
| 5cbd4acaca | |||
| 18ff12030c | |||
| 8898d95f4f | |||
| 33608d18f7 | |||
| acd12a4705 | |||
| 81557b8633 | |||
| e1b9842236 | |||
| 26cb2cdb5f | |||
| 5ebbfbbefe | |||
| ac49626466 | |||
| d332939666 | |||
| 2577009bcb | |||
| a58ad23e7f | |||
| ee4b5d33e0 | |||
| 625898f6eb | |||
| 8d257fed50 | |||
| 4f6b70e29a | |||
| 202bacc71b | |||
| 2c09684db9 | |||
| 282a81e1fc | |||
| ce7c8f066f | |||
| 25ded46b9d | |||
| 56e4abca5e | |||
| 4bd69f56a9 | |||
| 04921d7d06 | |||
| 51b95a5ca2 | |||
| 49257c6f33 | |||
| 895952654c | |||
| 0fd84a1b0d | |||
| d35174fe93 | |||
| f80ed6c460 | |||
| 72bc167726 | |||
| 21d3af2857 | |||
| a80355209a | |||
| 92589546e8 | |||
| b9146889f3 |
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Blue Green Bug Bash
|
||||
about: Issues found in blue-green strategy bug bash
|
||||
title: "[Blue-Green Bug Bash] "
|
||||
labels: 'blue-green-bug-bash'
|
||||
assignees: ajinkya599
|
||||
|
||||
---
|
||||
|
||||
Repro steps:
|
||||
- Add steps to repro the issue here
|
||||
-
|
||||
|
||||
Current behaviour:
|
||||
- What is the current behaviour?
|
||||
-
|
||||
|
||||
Expected behaviour:
|
||||
- What is the expected behaviour?
|
||||
-
|
||||
@@ -1,32 +0,0 @@
|
||||
token=$1
|
||||
commit=$2
|
||||
repository=$3
|
||||
prNumber=$4
|
||||
frombranch=$5
|
||||
tobranch=$6
|
||||
|
||||
getPayLoad() {
|
||||
cat <<EOF
|
||||
{
|
||||
"event_type": "K8sDeployActionPR",
|
||||
"client_payload":
|
||||
{
|
||||
"action": "CreateSecret",
|
||||
"commit": "$commit",
|
||||
"repository": "$repository",
|
||||
"prNumber": "$prNumber",
|
||||
"tobranch": "$tobranch",
|
||||
"frombranch": "$frombranch"
|
||||
}
|
||||
}
|
||||
EOF
|
||||
}
|
||||
|
||||
response=$(curl -X POST -H "Authorization: token $token" https://api.github.com/repos/Azure/azure-actions-integration-tests/dispatches --data "$(getPayLoad)")
|
||||
|
||||
if [ "$response" == "" ]; then
|
||||
echo "Integration tests triggered successfully"
|
||||
else
|
||||
echo "Triggering integration tests failed with: '$response'"
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,36 @@
|
||||
name: setting-default-labels
|
||||
|
||||
# Controls when the action will run.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0/3 * * *"
|
||||
|
||||
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
|
||||
jobs:
|
||||
build:
|
||||
# The type of runner that the job will run on
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# Steps represent a sequence of tasks that will be executed as part of the job
|
||||
steps:
|
||||
|
||||
- uses: actions/stale@v3
|
||||
name: Setting issue as idle
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-issue-message: 'This issue is idle because it has been open for 14 days with no activity.'
|
||||
stale-issue-label: 'idle'
|
||||
days-before-stale: 14
|
||||
days-before-close: -1
|
||||
operations-per-run: 100
|
||||
exempt-issue-labels: 'backlog'
|
||||
|
||||
- uses: actions/stale@v3
|
||||
name: Setting PR as idle
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-pr-message: 'This PR is idle because it has been open for 14 days with no activity.'
|
||||
stale-pr-label: 'idle'
|
||||
days-before-stale: 14
|
||||
days-before-close: -1
|
||||
operations-per-run: 100
|
||||
@@ -1,23 +0,0 @@
|
||||
name: "Trigger Integration tests"
|
||||
on:
|
||||
# push:
|
||||
# branches:
|
||||
# - master
|
||||
# - 'releases/*'
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
- 'releases/*'
|
||||
jobs:
|
||||
trigger-integration-tests:
|
||||
name: Trigger Integration tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
path: IntegrationTests
|
||||
|
||||
- name: Trigger Test run
|
||||
run: |
|
||||
bash ./IntegrationTests/.github/workflows/TriggerIntegrationTests.sh ${{ secrets.L2_REPO_TOKEN }} ${{ github.event.pull_request.head.sha }} ${{ github.repository }} ${{ github.event.pull_request.number }} ${{ github.event.pull_request.head.ref }} ${{ github.event.pull_request.base.ref }}
|
||||
@@ -0,0 +1,199 @@
|
||||
name: Minikube Integration Tests
|
||||
on: pull_request
|
||||
|
||||
jobs:
|
||||
run-integration-test:
|
||||
name: Run Minikube Integration Tests
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
KUBECONFIG: /home/runner/.kube/config
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Building latest changes
|
||||
run: |
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
- name: Set name of ns
|
||||
run: echo "::set-output name=name::$(echo `date +%Y%m%d%H%M%S`)"
|
||||
shell: bash
|
||||
id: ns
|
||||
|
||||
- uses: Azure/setup-kubectl@v1
|
||||
name: Install Kubectl
|
||||
|
||||
- id: setup-minikube
|
||||
name: Setup Minikube
|
||||
uses: manusa/actions-setup-minikube@v2.4.2
|
||||
with:
|
||||
minikube version: "v1.24.0"
|
||||
kubernetes version: "v1.17.8"
|
||||
driver: "none"
|
||||
timeout-minutes: 3
|
||||
|
||||
- name: Create namespace to run tests
|
||||
run: kubectl create ns test-${{ steps.ns.outputs.name }}
|
||||
|
||||
- uses: actions/setup-python@v2
|
||||
name: Install Python
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
- name: Cleaning any previously created items
|
||||
run: |
|
||||
python test/integration/k8s-deploy-delete.py 'Service' 'nginx-service' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-delete.py 'Service' 'nginx-service-green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-delete.py 'Deployment' 'nginx-deployment-green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-delete.py 'Deployment' 'nginx-deployment' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-delete.py 'Ingress' 'nginx-ingress' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Executing deploy action
|
||||
uses: ./
|
||||
with:
|
||||
namespace: test-${{ steps.ns.outputs.name }}
|
||||
images: nginx:1.14.2
|
||||
manifests: |
|
||||
test/integration/manifests/test-service.yml
|
||||
strategy: blue-green
|
||||
route-method: service
|
||||
action: deploy
|
||||
|
||||
- name: Checking if deploments and services were created with green labels
|
||||
run: |
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment-green' 'green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service' 'green' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Executing promote action
|
||||
uses: ./
|
||||
with:
|
||||
namespace: test-${{ steps.ns.outputs.name }}
|
||||
images: nginx:1.14.2
|
||||
manifests: |
|
||||
test/integration/manifests/test-service.yml
|
||||
strategy: blue-green
|
||||
route-method: service
|
||||
action: promote
|
||||
|
||||
- name: Checking if deploments and services were created with none labels after promote
|
||||
run: |
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment' 'None' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service' 'None' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Executing deploy action on
|
||||
uses: ./
|
||||
with:
|
||||
namespace: test-${{ steps.ns.outputs.name }}
|
||||
images: nginx:1.19.1
|
||||
manifests: |
|
||||
test/integration/manifests/test-service.yml
|
||||
strategy: blue-green
|
||||
route-method: service
|
||||
action: deploy
|
||||
|
||||
- name: Checking if deploments and services were created with green labels, and old workloads persist on deploy
|
||||
run: |
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment-green' 'green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service' 'green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment' 'None' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Executing reject action
|
||||
uses: ./
|
||||
with:
|
||||
namespace: test-${{ steps.ns.outputs.name }}
|
||||
images: nginx:1.19.1
|
||||
manifests: |
|
||||
test/integration/manifests/test-service.yml
|
||||
strategy: blue-green
|
||||
route-method: service
|
||||
action: reject
|
||||
|
||||
- name: Checking if deploments and services were routed back to none labels after reject
|
||||
run: |
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment' 'None' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service' 'None' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Cleaning up current set up
|
||||
run: |
|
||||
python test/integration/k8s-deploy-delete.py 'Service' 'nginx-service' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-delete.py 'Deployment' 'nginx-deployment' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Executing deploy action for ingress
|
||||
uses: ./
|
||||
with:
|
||||
namespace: test-${{ steps.ns.outputs.name }}
|
||||
images: nginx:1.14.2
|
||||
manifests: |
|
||||
test/integration/manifests/test-ingress.yml
|
||||
strategy: blue-green
|
||||
route-method: ingress
|
||||
action: deploy
|
||||
|
||||
- name: Checking if deploments, services and ingresses were created with green labels
|
||||
run: |
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment-green' 'green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service-green' 'green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Ingress' 'nginx-ingress' 'green' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Executing promote action for ingress
|
||||
uses: ./
|
||||
with:
|
||||
namespace: test-${{ steps.ns.outputs.name }}
|
||||
images: nginx:1.14.2
|
||||
manifests: |
|
||||
test/integration/manifests/test-ingress.yml
|
||||
strategy: blue-green
|
||||
route-method: ingress
|
||||
action: promote
|
||||
|
||||
- name: Checking if deploments, services and ingresses were created with none labels after promote
|
||||
run: |
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment' 'None' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service' 'None' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Ingress' 'nginx-ingress' 'None' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Executing deploy action for ingress
|
||||
uses: ./
|
||||
with:
|
||||
namespace: test-${{ steps.ns.outputs.name }}
|
||||
images: nginx:1.19.1
|
||||
manifests: |
|
||||
test/integration/manifests/test-ingress.yml
|
||||
strategy: blue-green
|
||||
route-method: ingress
|
||||
action: deploy
|
||||
|
||||
- name: Checking if deploments, services and ingresses were created with green labels after deploy, and old deployment persists
|
||||
run: |
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment-green' 'green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment' 'None' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service' 'None' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service-green' 'green' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Ingress' 'nginx-ingress' 'green' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- name: Executing reject action for ingress
|
||||
uses: ./
|
||||
with:
|
||||
namespace: test-${{ steps.ns.outputs.name }}
|
||||
images: nginx:1.19.1
|
||||
manifests: |
|
||||
test/integration/manifests/test-ingress.yml
|
||||
strategy: blue-green
|
||||
route-method: ingress
|
||||
action: reject
|
||||
|
||||
- name: Checking if deploments, services and ingresses were created with none labels after reject
|
||||
run: |
|
||||
python test/integration/k8s-deploy-test.py 'Deployment' 'nginx-deployment' 'None' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Service' 'nginx-service' 'None' ${{ steps.ns.outputs.name }}
|
||||
python test/integration/k8s-deploy-test.py 'Ingress' 'nginx-ingress' 'None' ${{ steps.ns.outputs.name }}
|
||||
|
||||
- if: ${{ always() }}
|
||||
name: Delete created namespace
|
||||
run: kubectl delete ns test-${{ steps.ns.outputs.name }}
|
||||
|
||||
- if: ${{ always() }}
|
||||
name: Posting result back to PR
|
||||
run: |
|
||||
if [ '${{ steps.job-type.outputs.type }}' == 'pr' ]; then ruby postStatus.rb ${{github.event.client_payload.repository}} ${{github.event.client_payload.commit}} ${{secrets.L2_REPO_TOKEN}} ${{job.status}} ${{github.run_id}} ${{matrix.os}} false ${{ secrets.L2_REPO_USER }}; fi
|
||||
shell: bash
|
||||
@@ -1,4 +1,4 @@
|
||||
name: "build-test"
|
||||
name: "Run unit tests."
|
||||
on: # rebuild any PRs and main branch changes
|
||||
pull_request:
|
||||
branches:
|
||||
@@ -16,5 +16,4 @@ jobs:
|
||||
- uses: actions/checkout@v1
|
||||
- run: |
|
||||
npm install
|
||||
npm build
|
||||
npm test
|
||||
+1
-329
@@ -1,329 +1 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUNIT
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
**/Properties/launchSettings.json
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_i.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
.JustCode
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# JetBrains Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
# CodeRush
|
||||
.cr/
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
.DS_Store
|
||||
@@ -103,7 +103,7 @@ Following are the key capabilities of this action:
|
||||
### Basic deployment (without any deployment strategy)
|
||||
|
||||
```yaml
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
namespace: 'myapp'
|
||||
manifests: |
|
||||
@@ -119,7 +119,7 @@ Following are the key capabilities of this action:
|
||||
### Deployment Strategies - Canary deployment without service mesh
|
||||
|
||||
```yaml
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
namespace: 'myapp'
|
||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
||||
@@ -136,7 +136,7 @@ Following are the key capabilities of this action:
|
||||
### To promote/reject the canary created by the above snippet, the following YAML snippet could be used:
|
||||
|
||||
```yaml
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
namespace: 'myapp'
|
||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
||||
@@ -153,7 +153,7 @@ Following are the key capabilities of this action:
|
||||
### Deployment Strategies - Canary deployment based on Service Mesh Interface
|
||||
|
||||
```yaml
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
namespace: 'myapp'
|
||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
||||
@@ -170,7 +170,7 @@ Following are the key capabilities of this action:
|
||||
```
|
||||
### To promote/reject the canary created by the above snippet, the following YAML snippet could be used:
|
||||
```yaml
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
namespace: 'myapp'
|
||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} '
|
||||
@@ -187,7 +187,7 @@ Following are the key capabilities of this action:
|
||||
### Deployment Strategies - Blue-Green deployment with different route methods
|
||||
|
||||
```yaml
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
namespace: 'myapp'
|
||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
||||
@@ -206,7 +206,7 @@ Following are the key capabilities of this action:
|
||||
### **To promote/reject the green workload created by the above snippet, the following YAML snippet could be used:**
|
||||
|
||||
```yaml
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
namespace: 'myapp'
|
||||
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
|
||||
@@ -218,7 +218,7 @@ Following are the key capabilities of this action:
|
||||
service.yaml
|
||||
ingress-yml
|
||||
strategy: blue-green
|
||||
strategy: ingress # should be the same as the value when action was deploy
|
||||
route-method: ingress # should be the same as the value when action was deploy
|
||||
action: promote # substitute reject if you want to reject
|
||||
```
|
||||
|
||||
@@ -261,7 +261,7 @@ jobs:
|
||||
container-registry-password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
secret-name: demo-k8s-secret
|
||||
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
manifests: |
|
||||
manifests/deployment.yml
|
||||
@@ -304,7 +304,7 @@ jobs:
|
||||
container-registry-password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
secret-name: demo-k8s-secret
|
||||
|
||||
- uses: Azure/k8s-deploy@v1
|
||||
- uses: Azure/k8s-deploy@v1.4
|
||||
with:
|
||||
manifests: |
|
||||
manifests/deployment.yml
|
||||
@@ -314,6 +314,138 @@ jobs:
|
||||
imagepullsecrets: |
|
||||
demo-k8s-secret
|
||||
```
|
||||
## Sample workflows for new traceability fields support
|
||||
|
||||
- Environment variable `HELM_CHART_PATHS` is a list of helmchart files expected by k8s-deploy - it will be populated automatically if you are using `k8s-bake` to generate the manifests.
|
||||
- Use script to build image and add `dockerfile-path` label to it.
|
||||
The value expected is the link to the dockerfile : `https://github.com/${{github.repo}}/blob/${{github.sha}}/Dockerfile`
|
||||
If your dockerfile is in the same repo and branch where the workflow is run, it can be a relative path and it will be converted to a link for traceability.
|
||||
- Run docker login action for each image registry - in case image build and image deploy are 2 distinct jobs in the same or separate workflows.
|
||||
|
||||
### End to end workflow for building and deploying container images
|
||||
|
||||
```yaml
|
||||
on: [push]
|
||||
env:
|
||||
NAMESPACE: demo-ns2
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
|
||||
- uses: Azure/docker-login@v1
|
||||
with:
|
||||
login-server: contoso.azurecr.io
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- run: |
|
||||
docker build . -t contoso.azurecr.io/k8sdemo:${{ github.sha }} --label dockerfile-path=./Dockerfile
|
||||
docker push contoso.azurecr.io/k8sdemo:${{ github.sha }}
|
||||
|
||||
# Set the target AKS cluster.
|
||||
- uses: Azure/aks-set-context@v1
|
||||
with:
|
||||
creds: '${{ secrets.AZURE_CREDENTIALS }}'
|
||||
cluster-name: contoso
|
||||
resource-group: contoso-rg
|
||||
|
||||
- uses: Azure/k8s-create-secret@v1
|
||||
with:
|
||||
container-registry-url: contoso.azurecr.io
|
||||
container-registry-username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
container-registry-password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
secret-name: demo-k8s-secret
|
||||
|
||||
- uses: Azure/k8s-deploy@v1.2
|
||||
with:
|
||||
manifests: |
|
||||
manifests/deployment.yml
|
||||
manifests/service.yml
|
||||
images: |
|
||||
contoso.azurecr.io/k8sdemo:${{ github.sha }}
|
||||
imagepullsecrets: |
|
||||
demo-k8s-secret
|
||||
```
|
||||
|
||||
### CI workflow to build image and add `dockerfile-path` label to it. This image can then be used in another CD workflow.
|
||||
|
||||
```yaml
|
||||
on: [push]
|
||||
env:
|
||||
NAMESPACE: demo-ns2
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
|
||||
- uses: Azure/docker-login@v1
|
||||
with:
|
||||
login-server: contoso.azurecr.io
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- run: |
|
||||
docker build . -t contoso.azurecr.io/k8sdemo:${{ github.sha }} --label dockerfile-path=https://github.com/${{github.repo}}/blob/${{github.sha}}/Dockerfile
|
||||
docker push contoso.azurecr.io/k8sdemo:${{ github.sha }}
|
||||
```
|
||||
|
||||
### CD workflow using bake action to get manifests deploying to a Kubernetes cluster
|
||||
|
||||
```yaml
|
||||
on: [push]
|
||||
env:
|
||||
NAMESPACE: demo-ns2
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
|
||||
- uses: Azure/docker-login@v1
|
||||
with:
|
||||
login-server: contoso.azurecr.io
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
# Set the target AKS cluster.
|
||||
- uses: Azure/aks-set-context@v1
|
||||
with:
|
||||
creds: '${{ secrets.AZURE_CREDENTIALS }}'
|
||||
cluster-name: contoso
|
||||
resource-group: contoso-rg
|
||||
|
||||
- uses: Azure/k8s-create-secret@v1
|
||||
with:
|
||||
namespace: ${{ env.NAMESPACE }}
|
||||
container-registry-url: contoso.azurecr.io
|
||||
container-registry-username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
container-registry-password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
secret-name: demo-k8s-secret
|
||||
|
||||
- uses: azure/k8s-bake@v1
|
||||
with:
|
||||
renderEngine: 'helm'
|
||||
helmChart: './aks-helloworld/'
|
||||
overrideFiles: './aks-helloworld/values-override.yaml'
|
||||
overrides: |
|
||||
replicas:2
|
||||
helm-version: 'latest'
|
||||
id: bake
|
||||
|
||||
- uses: Azure/k8s-deploy@v1.2
|
||||
with:
|
||||
manifests: ${{ steps.bake.outputs.manifestsBundle }}
|
||||
images: |
|
||||
contoso.azurecr.io/k8sdemo:${{ github.sha }}
|
||||
imagepullsecrets: |
|
||||
demo-k8s-secret
|
||||
```
|
||||
|
||||
# Contributing
|
||||
|
||||
@@ -327,4 +459,4 @@ provided by the bot. You will only need to do this once across all repos using o
|
||||
|
||||
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
|
||||
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
|
||||
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
|
||||
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
|
||||
|
||||
+217
-22
@@ -6,11 +6,14 @@ import * as deployment from '../src/utilities/strategy-helpers/deployment-helper
|
||||
import * as fs from 'fs';
|
||||
import * as io from '@actions/io';
|
||||
import * as toolCache from '@actions/tool-cache';
|
||||
import * as util from 'util';
|
||||
import * as fileHelper from '../src/utilities/files-helper';
|
||||
import { workflowAnnotations } from '../src/constants';
|
||||
import { getWorkflowAnnotationKeyLabel, getWorkflowAnnotationsJson } from '../src/constants';
|
||||
import * as inputParam from '../src/input-parameters';
|
||||
|
||||
import { Kubectl, Resource } from '../src/kubectl-object-model';
|
||||
import * as httpClient from '../src/utilities/httpClient';
|
||||
import * as utility from '../src/utilities/utility';
|
||||
|
||||
import { getkubectlDownloadURL } from "../src/utilities/kubectl-util";
|
||||
import { mocked } from 'ts-jest/utils';
|
||||
@@ -21,6 +24,7 @@ const os = require("os");
|
||||
const coreMock = mocked(core, true);
|
||||
const ioMock = mocked(io, true);
|
||||
const inputParamMock = mocked(inputParam, true);
|
||||
const osMock = mocked(os, true);
|
||||
|
||||
const toolCacheMock = mocked(toolCache, true);
|
||||
const fileUtility = mocked(fs, true);
|
||||
@@ -36,14 +40,48 @@ const getAllPodsMock = {
|
||||
|
||||
const getNamespaceMock = {
|
||||
'code': 0,
|
||||
'stdout': '{"apiVersion": "v1","kind": "Namespace","metadata": {"annotations": {"workflow": ".github/workflows/workflow.yml","runUri": "https://github.com/testRepo/actions/runs/12345"}},"spec": {"finalizers": ["kubernetes"]},"status": {"phase": "Active"}}'
|
||||
'stdout': '{"apiVersion": "v1","kind": "Namespace","metadata": {"annotations": {"githubWorkflow_c11401b9d232942bac19cbc5bc32b42d": "{\'run\': \'202489005\',\'repository\': \'testUser/hello-kubernetes\',\'workflow\': \'workflow1\',\'jobName\': \'build-and-deploy\',\'createdBy\': \'testUser\',\'runUri\': \'https://github.com/testUser/hello-kubernetes/actions/runs/202489005\',\'commit\': \'currentCommit\',\'lastSuccessRunCommit\': \'lastCommit\',\'branch\': \'refs/heads/branch-rename\',\'deployTimestamp\': \'1597062957973\',\'dockerfilePaths\': \'{}\',\'manifestsPaths\': \'[]\',\'helmChartPaths\': \'[]\',\'provider\': \'GitHub\'}","githubWorkflow_21fd7a597282ca5adc05ba99018b3706": "{\'run\': \'202504411\',\'repository\': \'testUser/hello-kubernetes\',\'workflow\': \'workflowMaster\',\'jobName\': \'build-and-deploy\',\'createdBy\': \'testUser\',\'runUri\': \'https://github.com/testUser/hello-kubernetes/actions/runs/202504411\',\'commit\': \'currentCommit1\',\'lastSuccessRunCommit\': \'NA\',\'branch\': \'refs/heads/master\',\'deployTimestamp\': \'1597063919873\',\'dockerfilePaths\': \'{}\',\'manifestsPaths\': \'[]\',\'helmChartPaths\': \'[]\',\'provider\': \'GitHub\'}"}},"spec": {"finalizers": ["kubernetes"]},"status": {"phase": "Active"}}'
|
||||
};
|
||||
|
||||
const getWorkflowsUrlResponse = {
|
||||
'statusCode': httpClient.StatusCodes.OK,
|
||||
'body': {
|
||||
"total_count": 2,
|
||||
"workflows": [
|
||||
{
|
||||
"id": 1477727,
|
||||
"node_id": "MDg6V29ya2Zsb3cxNDYwNzI3",
|
||||
"name": ".github/workflows/workflow.yml",
|
||||
"path": ".github/workflows/workflow.yml",
|
||||
"state": "active",
|
||||
"created_at": "2020-06-03T23:41:06.000+05:30",
|
||||
"updated_at": "2020-08-07T15:46:42.000+05:30",
|
||||
"url": "https://api.github.com/repos/testUser/hello-kubernetes/actions/workflows/1460727",
|
||||
"html_url": "https://github.com/testUser/hello-kubernetes/blob/master/.github/workflows/workflow.yml",
|
||||
"badge_url": "https://github.com/testUser/hello-kubernetes/workflows/.github/workflows/workflow.yml/badge.svg"
|
||||
},
|
||||
{
|
||||
"id": 1532230,
|
||||
"node_id": "MDg6V29ya2Zsb3cxNTMyMzMw",
|
||||
"name": "NewWorkflow",
|
||||
"path": ".github/workflows/workflow1.yml",
|
||||
"state": "active",
|
||||
"created_at": "2020-06-11T16:05:23.000+05:30",
|
||||
"updated_at": "2020-08-07T15:46:42.000+05:30",
|
||||
"url": "https://api.github.com/repos/testUser/hello-kubernetes/actions/workflows/1532330",
|
||||
"html_url": "https://github.com/testUser/hello-kubernetes/blob/master/.github/workflows/workflowNew.yml",
|
||||
"badge_url": "https://github.com/testUser/hello-kubernetes/workflows/KoDeyi/badge.svg"
|
||||
}
|
||||
]
|
||||
}
|
||||
} as httpClient.WebResponse;
|
||||
|
||||
const resources: Resource[] = [{ type: "Deployment", name: "AppName" }];
|
||||
|
||||
beforeEach(() => {
|
||||
deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'deployment.yml'), 'utf8');
|
||||
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => 1234561234567);
|
||||
|
||||
process.env["KUBECONFIG"] = 'kubeConfig';
|
||||
process.env['GITHUB_RUN_ID'] = '12345';
|
||||
process.env['GITHUB_WORKFLOW'] = '.github/workflows/workflow.yml';
|
||||
@@ -52,12 +90,18 @@ beforeEach(() => {
|
||||
process.env['GITHUB_REPOSITORY'] = 'testRepo';
|
||||
process.env['GITHUB_SHA'] = 'testCommit';
|
||||
process.env['GITHUB_REF'] = 'testBranch';
|
||||
process.env['GITHUB_TOKEN'] = 'testToken';
|
||||
})
|
||||
|
||||
test("setKubectlPath() - install a particular version", async () => {
|
||||
test.each([
|
||||
['arm', 'arm'],
|
||||
['arm64', 'arm64'],
|
||||
['x64', 'amd64']
|
||||
])("setKubectlPath() - install a particular version on %s", async (osArch, kubectlArch) => {
|
||||
const kubectlVersion = 'v1.18.0'
|
||||
//Mocks
|
||||
coreMock.getInput = jest.fn().mockReturnValue(kubectlVersion);
|
||||
osMock.arch = jest.fn().mockReturnValue(osArch);
|
||||
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
||||
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
|
||||
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
|
||||
@@ -66,7 +110,7 @@ test("setKubectlPath() - install a particular version", async () => {
|
||||
//Invoke and assert
|
||||
await expect(action.run()).resolves.not.toThrow();
|
||||
expect(toolCacheMock.find).toBeCalledWith('kubectl', kubectlVersion);
|
||||
expect(toolCacheMock.downloadTool).toBeCalledWith(getkubectlDownloadURL(kubectlVersion));
|
||||
expect(toolCacheMock.downloadTool).toBeCalledWith(getkubectlDownloadURL(kubectlVersion, kubectlArch));
|
||||
});
|
||||
|
||||
test("setKubectlPath() - install a latest version", async () => {
|
||||
@@ -166,6 +210,111 @@ test("run() - deploy - Manifiest not provided", async () => {
|
||||
expect(coreMock.setFailed).toBeCalledWith('No manifests supplied to deploy');
|
||||
});
|
||||
|
||||
test("run() - deploy - Only one manifest with no delimiters", async () => {
|
||||
const kubectlVersion = 'v1.18.0'
|
||||
coreMock.getInput = jest.fn().mockImplementation((name) => {
|
||||
if (name == 'manifests') {
|
||||
return "bg-smi.yml";
|
||||
}
|
||||
if (name == 'action') {
|
||||
return 'deploy';
|
||||
}
|
||||
return kubectlVersion;
|
||||
});
|
||||
coreMock.setFailed = jest.fn();
|
||||
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
||||
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
|
||||
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
|
||||
fileUtility.chmodSync = jest.fn();
|
||||
|
||||
//Invoke and assert
|
||||
await expect(action.run()).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
test("run() - deploy - Manifests provided by new line delimiter", async () => {
|
||||
const kubectlVersion = 'v1.18.0'
|
||||
coreMock.getInput = jest.fn().mockImplementation((name) => {
|
||||
if (name == 'manifests') {
|
||||
return "bg-smi.yml\n bg.yml\ndeployment.yml";
|
||||
}
|
||||
if (name == 'action') {
|
||||
return 'deploy';
|
||||
}
|
||||
return kubectlVersion;
|
||||
});
|
||||
coreMock.setFailed = jest.fn();
|
||||
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
||||
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
|
||||
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
|
||||
fileUtility.chmodSync = jest.fn();
|
||||
|
||||
//Invoke and assert
|
||||
await expect(action.run()).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
test("run() - deploy - Manifests provided by comma as a delimiter", async () => {
|
||||
const kubectlVersion = 'v1.18.0'
|
||||
coreMock.getInput = jest.fn().mockImplementation((name) => {
|
||||
if (name == 'manifests') {
|
||||
return "bg-smi.yml, bg.yml, deployment.yml";
|
||||
}
|
||||
if (name == 'action') {
|
||||
return 'deploy';
|
||||
}
|
||||
return kubectlVersion;
|
||||
});
|
||||
coreMock.setFailed = jest.fn();
|
||||
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
||||
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
|
||||
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
|
||||
fileUtility.chmodSync = jest.fn();
|
||||
|
||||
//Invoke and assert
|
||||
await expect(action.run()).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
test("run() - deploy - Manifests provided by both new line and comma as a delimiter", async () => {
|
||||
const kubectlVersion = 'v1.18.0'
|
||||
coreMock.getInput = jest.fn().mockImplementation((name) => {
|
||||
if (name == 'manifests') {
|
||||
return "bg-smi.yml\nbg.yml,deployment.yml";
|
||||
}
|
||||
if (name == 'action') {
|
||||
return 'deploy';
|
||||
}
|
||||
return kubectlVersion;
|
||||
});
|
||||
coreMock.setFailed = jest.fn();
|
||||
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
||||
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
|
||||
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
|
||||
fileUtility.chmodSync = jest.fn();
|
||||
|
||||
//Invoke and assert
|
||||
await expect(action.run()).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
test("run() - deploy - Manifests provided by both new line and comma and semi-colon as a delimiter", async () => {
|
||||
const kubectlVersion = 'v1.18.0'
|
||||
coreMock.getInput = jest.fn().mockImplementation((name) => {
|
||||
if (name == 'manifests') {
|
||||
return "bg-smi.yml\nbg.yml,deployment.yml;bg.yml";
|
||||
}
|
||||
if (name == 'action') {
|
||||
return 'deploy';
|
||||
}
|
||||
return kubectlVersion;
|
||||
});
|
||||
coreMock.setFailed = jest.fn();
|
||||
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
||||
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
|
||||
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
|
||||
fileUtility.chmodSync = jest.fn();
|
||||
|
||||
//Invoke and assert
|
||||
await expect(action.run()).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
test("deployment - deploy() - Invokes with no manifestfiles", async () => {
|
||||
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
|
||||
|
||||
@@ -213,9 +362,11 @@ test("deployment - deploy() - Invokes with manifestfiles", async () => {
|
||||
kubeCtl.describe = jest.fn().mockReturnValue("");
|
||||
kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
|
||||
kubeCtl.annotate = jest.fn().mockReturnValue("");
|
||||
kubeCtl.labelFiles = jest.fn().mockReturnValue("");
|
||||
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
||||
|
||||
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
|
||||
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
|
||||
|
||||
//Invoke and assert
|
||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||
@@ -241,9 +392,11 @@ test("deployment - deploy() - deploy force flag on", async () => {
|
||||
kubeCtl.describe = jest.fn().mockReturnValue("");
|
||||
kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
|
||||
kubeCtl.annotate = jest.fn().mockReturnValue("");
|
||||
kubeCtl.labelFiles = jest.fn().mockReturnValue("");
|
||||
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
||||
|
||||
const deploySpy = jest.spyOn(kubeCtl, 'apply').mockImplementation(() => applyResMock);
|
||||
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
|
||||
|
||||
//Invoke and assert
|
||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||
@@ -251,15 +404,20 @@ test("deployment - deploy() - deploy force flag on", async () => {
|
||||
deploySpy.mockRestore();
|
||||
});
|
||||
|
||||
test("deployment - deploy() - Annotate resources", async () => {
|
||||
test("deployment - deploy() - Annotate & label resources", async () => {
|
||||
let deploymentConfig: utility.DeploymentConfig = { manifestFilePaths: ['manifests/deployment.yaml'], helmChartFilePaths: [], dockerfilePaths: {} };
|
||||
let annotationKeyValStr = getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW) + '=' + getWorkflowAnnotationsJson('currentCommit', '.github/workflows/workflow.yml', deploymentConfig);
|
||||
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
|
||||
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
||||
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
|
||||
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
|
||||
const fileHelperMock = mocked(fileHelper, true);
|
||||
const fsMock = (mocked(fs, true));
|
||||
fileHelperMock.getTempDirectory = jest.fn().mockReturnValue("Local/Temp/");
|
||||
fsMock.writeFileSync =jest.fn().mockReturnValue("");
|
||||
fileHelperMock.getTempDirectory = jest.fn().mockReturnValue("~/Deployment_testapp_currentTimestamp");
|
||||
fsMock.writeFileSync = jest.fn().mockReturnValue("");
|
||||
jest.spyOn(utility, 'getWorkflowFilePath').mockImplementation(() => Promise.resolve(process.env.GITHUB_WORKFLOW));
|
||||
jest.spyOn(utility, 'getDeploymentConfig').mockImplementation(() => Promise.resolve(deploymentConfig));
|
||||
|
||||
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
|
||||
kubeCtl.apply = jest.fn().mockReturnValue("");
|
||||
kubeCtl.getResource = jest.fn().mockReturnValue(getNamespaceMock);
|
||||
@@ -267,23 +425,31 @@ test("deployment - deploy() - Annotate resources", async () => {
|
||||
kubeCtl.getNewReplicaSet = jest.fn().mockReturnValue("testpod-776cbc86f9");
|
||||
kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
|
||||
kubeCtl.annotate = jest.fn().mockReturnValue("");
|
||||
|
||||
kubeCtl.labelFiles = jest.fn();
|
||||
//Invoke and assert
|
||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||
expect(kubeCtl.annotateFiles).toBeCalledWith(["Local/Temp/deployment.yaml"], workflowAnnotations, true);
|
||||
expect(kubeCtl.annotate).toHaveBeenNthCalledWith(1, 'namespace', 'default', annotationKeyValStr);
|
||||
expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp/deployment.yaml"], annotationKeyValStr);
|
||||
expect(kubeCtl.annotate).toBeCalledTimes(2);
|
||||
expect(kubeCtl.labelFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp/deployment.yaml"],
|
||||
[`workflowFriendlyName=workflow.yml`, `workflow=${getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW)}`]);
|
||||
});
|
||||
|
||||
test("deployment - deploy() - Skip Annotate namespace", async () => {
|
||||
process.env['GITHUB_REPOSITORY'] = 'test1Repo';
|
||||
test("deployment - deploy() - Annotate & label resources for a new workflow", async () => {
|
||||
process.env.GITHUB_WORKFLOW = '.github/workflows/New Workflow.yml';
|
||||
let deploymentConfig: utility.DeploymentConfig = { manifestFilePaths: ['manifests/deployment.yaml'], helmChartFilePaths: [], dockerfilePaths: {} }
|
||||
let annotationKeyValStr = getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW) + '=' + getWorkflowAnnotationsJson('NA', '.github/workflows/New Workflow.yml', deploymentConfig);
|
||||
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
|
||||
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
||||
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
|
||||
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
|
||||
const fileHelperMock = mocked(fileHelper, true);
|
||||
const fsMock = (mocked(fs, true));
|
||||
fileHelperMock.getTempDirectory = jest.fn().mockReturnValue("Local/Temp/");
|
||||
fsMock.writeFileSync =jest.fn().mockReturnValue("");
|
||||
fileHelperMock.getTempDirectory = jest.fn().mockReturnValue("~/Deployment_testapp_currentTimestamp");
|
||||
fsMock.writeFileSync = jest.fn().mockReturnValue("");
|
||||
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
|
||||
jest.spyOn(utility, 'getDeploymentConfig').mockImplementation(() => Promise.resolve(deploymentConfig));
|
||||
|
||||
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
|
||||
kubeCtl.apply = jest.fn().mockReturnValue("");
|
||||
kubeCtl.getResource = jest.fn().mockReturnValue(getNamespaceMock);
|
||||
@@ -291,14 +457,14 @@ test("deployment - deploy() - Skip Annotate namespace", async () => {
|
||||
kubeCtl.getNewReplicaSet = jest.fn().mockReturnValue("testpod-776cbc86f9");
|
||||
kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
|
||||
kubeCtl.annotate = jest.fn().mockReturnValue("");
|
||||
|
||||
const consoleOutputSpy = jest.spyOn(process.stdout, "write").mockImplementation();
|
||||
|
||||
kubeCtl.labelFiles = jest.fn();
|
||||
//Invoke and assert
|
||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||
expect(kubeCtl.annotateFiles).toBeCalledWith(["Local/Temp/deployment.yaml"], workflowAnnotations, true);
|
||||
expect(kubeCtl.annotate).toBeCalledTimes(1);
|
||||
expect(consoleOutputSpy).toHaveBeenNthCalledWith(1, `##[debug]Skipping 'annotate namespace' as namespace annotated by other workflow` + os.EOL)
|
||||
expect(kubeCtl.annotate).toHaveBeenNthCalledWith(1, 'namespace', 'default', annotationKeyValStr);
|
||||
expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp/deployment.yaml"], annotationKeyValStr);
|
||||
expect(kubeCtl.annotate).toBeCalledTimes(2);
|
||||
expect(kubeCtl.labelFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp/deployment.yaml"],
|
||||
[`workflowFriendlyName=New_Workflow.yml`, `workflow=${getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW)}`]);
|
||||
});
|
||||
|
||||
test("deployment - deploy() - Annotate resources failed", async () => {
|
||||
@@ -320,10 +486,39 @@ test("deployment - deploy() - Annotate resources failed", async () => {
|
||||
kubeCtl.describe = jest.fn().mockReturnValue("");
|
||||
kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
|
||||
kubeCtl.annotate = jest.fn().mockReturnValue(annotateMock);
|
||||
kubeCtl.labelFiles = jest.fn().mockReturnValue("");
|
||||
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
|
||||
|
||||
const consoleOutputSpy = jest.spyOn(process.stdout, "write").mockImplementation();
|
||||
//Invoke and assert
|
||||
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
|
||||
expect(consoleOutputSpy).toHaveBeenNthCalledWith(1, '##[warning]kubectl annotate failed' + os.EOL)
|
||||
});
|
||||
expect(consoleOutputSpy).toHaveBeenNthCalledWith(1, '::warning::kubectl annotate failed' + os.EOL)
|
||||
});
|
||||
|
||||
test("utility - getWorkflowFilePath() - Get workflow file path under API failure", async () => {
|
||||
//Mocks
|
||||
const errorWebResponse = {
|
||||
'statusCode': httpClient.StatusCodes.UNAUTHORIZED,
|
||||
'body': {}
|
||||
} as httpClient.WebResponse
|
||||
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(errorWebResponse));
|
||||
|
||||
//Invoke and assert
|
||||
await expect(utility.getWorkflowFilePath(process.env.GITHUB_TOKEN)).resolves.not.toThrowError;
|
||||
await expect(utility.getWorkflowFilePath(process.env.GITHUB_TOKEN)).resolves.toBe(process.env.GITHUB_WORKFLOW);
|
||||
});
|
||||
|
||||
test("action - run() - Throw kubectl error on 404 response", async () => {
|
||||
const kubectlVersion = 'v1.18.0'
|
||||
const arch = 'arm128';
|
||||
// Mock
|
||||
coreMock.getInput = jest.fn().mockReturnValue(kubectlVersion);
|
||||
osMock.arch = jest.fn().mockReturnValue(arch);
|
||||
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
|
||||
toolCacheMock.downloadTool = jest.fn().mockImplementation(_ => {
|
||||
throw new toolCache.HTTPError(httpClient.StatusCodes.NOT_FOUND);
|
||||
});
|
||||
|
||||
//Invoke and assert
|
||||
await expect(action.run()).rejects.toThrow(util.format("Kubectl '%s' for '%s' arch not found.", kubectlVersion, arch));
|
||||
});
|
||||
|
||||
@@ -53,6 +53,10 @@ inputs:
|
||||
description: 'Deploy when a previous deployment already exists. If true then --force argument is added to the apply command'
|
||||
required: false
|
||||
default: false
|
||||
token:
|
||||
description: 'Github token'
|
||||
default: ${{ github.token }}
|
||||
required: true
|
||||
|
||||
branding:
|
||||
color: 'green' # optional, decorates the entry in the GitHub Marketplace
|
||||
|
||||
+107
-107
@@ -1,107 +1,107 @@
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.promote = void 0;
|
||||
const core = require("@actions/core");
|
||||
const deploymentHelper = require("../utilities/strategy-helpers/deployment-helper");
|
||||
const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper");
|
||||
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
|
||||
const utils = require("../utilities/manifest-utilities");
|
||||
const TaskInputParameters = require("../input-parameters");
|
||||
const manifest_utilities_1 = require("../utilities/manifest-utilities");
|
||||
const KubernetesObjectUtility = require("../utilities/resource-object-utility");
|
||||
const models = require("../constants");
|
||||
const KubernetesManifestUtility = require("../utilities/manifest-stability-utility");
|
||||
const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
|
||||
const blue_green_helper_2 = require("../utilities/strategy-helpers/blue-green-helper");
|
||||
const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
|
||||
const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
|
||||
const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
|
||||
const kubectl_object_model_1 = require("../kubectl-object-model");
|
||||
function promote() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
|
||||
if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
|
||||
yield promoteCanary(kubectl);
|
||||
}
|
||||
else if (blue_green_helper_2.isBlueGreenDeploymentStrategy()) {
|
||||
yield promoteBlueGreen(kubectl);
|
||||
}
|
||||
else {
|
||||
core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
|
||||
throw ('InvalidPromotetActionDeploymentStrategy');
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.promote = promote;
|
||||
function promoteCanary(kubectl) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let includeServices = false;
|
||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||
includeServices = true;
|
||||
// In case of SMI traffic split strategy when deployment is promoted, first we will redirect traffic to
|
||||
// Canary deployment, then update stable deployment and then redirect traffic to stable deployment
|
||||
core.debug('Redirecting traffic to canary deployment');
|
||||
SMICanaryDeploymentHelper.redirectTrafficToCanaryDeployment(kubectl, TaskInputParameters.manifests);
|
||||
core.debug('Deploying input manifests with SMI canary strategy');
|
||||
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None');
|
||||
core.debug('Redirecting traffic to stable deployment');
|
||||
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests);
|
||||
}
|
||||
else {
|
||||
core.debug('Deploying input manifests');
|
||||
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None');
|
||||
}
|
||||
core.debug('Deployment strategy selected is Canary. Deleting canary and baseline workloads.');
|
||||
try {
|
||||
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
|
||||
}
|
||||
catch (ex) {
|
||||
core.warning('Exception occurred while deleting canary and baseline workloads. Exception: ' + ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
function promoteBlueGreen(kubectl) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
// updated container images and pull secrets
|
||||
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(TaskInputParameters.manifests);
|
||||
const manifestObjects = blue_green_helper_1.getManifestObjects(inputManifestFiles);
|
||||
core.debug('deleting old deployment and making new ones');
|
||||
let result;
|
||||
if (blue_green_helper_2.isIngressRoute()) {
|
||||
result = yield ingress_blue_green_helper_1.promoteBlueGreenIngress(kubectl, manifestObjects);
|
||||
}
|
||||
else if (blue_green_helper_2.isSMIRoute()) {
|
||||
result = yield smi_blue_green_helper_1.promoteBlueGreenSMI(kubectl, manifestObjects);
|
||||
}
|
||||
else {
|
||||
result = yield service_blue_green_helper_1.promoteBlueGreenService(kubectl, manifestObjects);
|
||||
}
|
||||
// checking stability of newly created deployments
|
||||
const deployedManifestFiles = result.newFilePaths;
|
||||
const resources = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([models.DiscoveryAndLoadBalancerResource.service]));
|
||||
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
|
||||
core.debug('routing to new deployments');
|
||||
if (blue_green_helper_2.isIngressRoute()) {
|
||||
ingress_blue_green_helper_1.routeBlueGreenIngress(kubectl, null, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
|
||||
blue_green_helper_1.deleteWorkloadsAndServicesWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList, manifestObjects.serviceEntityList);
|
||||
}
|
||||
else if (blue_green_helper_2.isSMIRoute()) {
|
||||
smi_blue_green_helper_1.routeBlueGreenSMI(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
|
||||
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
|
||||
smi_blue_green_helper_1.cleanupSMI(kubectl, manifestObjects.serviceEntityList);
|
||||
}
|
||||
else {
|
||||
service_blue_green_helper_1.routeBlueGreenService(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
|
||||
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
|
||||
}
|
||||
});
|
||||
}
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.promote = void 0;
|
||||
const core = require("@actions/core");
|
||||
const deploymentHelper = require("../utilities/strategy-helpers/deployment-helper");
|
||||
const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper");
|
||||
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
|
||||
const utils = require("../utilities/manifest-utilities");
|
||||
const TaskInputParameters = require("../input-parameters");
|
||||
const manifest_utilities_1 = require("../utilities/manifest-utilities");
|
||||
const KubernetesObjectUtility = require("../utilities/resource-object-utility");
|
||||
const models = require("../constants");
|
||||
const KubernetesManifestUtility = require("../utilities/manifest-stability-utility");
|
||||
const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
|
||||
const blue_green_helper_2 = require("../utilities/strategy-helpers/blue-green-helper");
|
||||
const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
|
||||
const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
|
||||
const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
|
||||
const kubectl_object_model_1 = require("../kubectl-object-model");
|
||||
function promote() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
|
||||
if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
|
||||
yield promoteCanary(kubectl);
|
||||
}
|
||||
else if (blue_green_helper_2.isBlueGreenDeploymentStrategy()) {
|
||||
yield promoteBlueGreen(kubectl);
|
||||
}
|
||||
else {
|
||||
core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
|
||||
throw ('InvalidPromotetActionDeploymentStrategy');
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.promote = promote;
|
||||
function promoteCanary(kubectl) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let includeServices = false;
|
||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||
includeServices = true;
|
||||
// In case of SMI traffic split strategy when deployment is promoted, first we will redirect traffic to
|
||||
// Canary deployment, then update stable deployment and then redirect traffic to stable deployment
|
||||
core.debug('Redirecting traffic to canary deployment');
|
||||
SMICanaryDeploymentHelper.redirectTrafficToCanaryDeployment(kubectl, TaskInputParameters.manifests);
|
||||
core.debug('Deploying input manifests with SMI canary strategy');
|
||||
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None');
|
||||
core.debug('Redirecting traffic to stable deployment');
|
||||
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests);
|
||||
}
|
||||
else {
|
||||
core.debug('Deploying input manifests');
|
||||
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None');
|
||||
}
|
||||
core.debug('Deployment strategy selected is Canary. Deleting canary and baseline workloads.');
|
||||
try {
|
||||
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
|
||||
}
|
||||
catch (ex) {
|
||||
core.warning('Exception occurred while deleting canary and baseline workloads. Exception: ' + ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
function promoteBlueGreen(kubectl) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
// updated container images and pull secrets
|
||||
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(TaskInputParameters.manifests);
|
||||
const manifestObjects = blue_green_helper_1.getManifestObjects(inputManifestFiles);
|
||||
core.debug('deleting old deployment and making new ones');
|
||||
let result;
|
||||
if (blue_green_helper_2.isIngressRoute()) {
|
||||
result = yield ingress_blue_green_helper_1.promoteBlueGreenIngress(kubectl, manifestObjects);
|
||||
}
|
||||
else if (blue_green_helper_2.isSMIRoute()) {
|
||||
result = yield smi_blue_green_helper_1.promoteBlueGreenSMI(kubectl, manifestObjects);
|
||||
}
|
||||
else {
|
||||
result = yield service_blue_green_helper_1.promoteBlueGreenService(kubectl, manifestObjects);
|
||||
}
|
||||
// checking stability of newly created deployments
|
||||
const deployedManifestFiles = result.newFilePaths;
|
||||
const resources = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([models.DiscoveryAndLoadBalancerResource.service]));
|
||||
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
|
||||
core.debug('routing to new deployments');
|
||||
if (blue_green_helper_2.isIngressRoute()) {
|
||||
ingress_blue_green_helper_1.routeBlueGreenIngress(kubectl, null, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
|
||||
blue_green_helper_1.deleteWorkloadsAndServicesWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList, manifestObjects.serviceEntityList);
|
||||
}
|
||||
else if (blue_green_helper_2.isSMIRoute()) {
|
||||
smi_blue_green_helper_1.routeBlueGreenSMI(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
|
||||
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
|
||||
smi_blue_green_helper_1.cleanupSMI(kubectl, manifestObjects.serviceEntityList);
|
||||
}
|
||||
else {
|
||||
service_blue_green_helper_1.routeBlueGreenService(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
|
||||
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+65
-65
@@ -1,65 +1,65 @@
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.reject = void 0;
|
||||
const core = require("@actions/core");
|
||||
const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper");
|
||||
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
|
||||
const kubectl_object_model_1 = require("../kubectl-object-model");
|
||||
const utils = require("../utilities/manifest-utilities");
|
||||
const TaskInputParameters = require("../input-parameters");
|
||||
const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
|
||||
const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
|
||||
const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
|
||||
const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
|
||||
const deployment_helper_1 = require("../utilities/strategy-helpers/deployment-helper");
|
||||
function reject() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
|
||||
if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
|
||||
yield rejectCanary(kubectl);
|
||||
}
|
||||
else if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
|
||||
yield rejectBlueGreen(kubectl);
|
||||
}
|
||||
else {
|
||||
core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
|
||||
throw ('InvalidDeletetActionDeploymentStrategy');
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.reject = reject;
|
||||
function rejectCanary(kubectl) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let includeServices = false;
|
||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||
core.debug('Reject deployment with SMI canary strategy');
|
||||
includeServices = true;
|
||||
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests);
|
||||
}
|
||||
core.debug('Deployment strategy selected is Canary. Deleting baseline and canary workloads.');
|
||||
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
|
||||
});
|
||||
}
|
||||
function rejectBlueGreen(kubectl) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let inputManifestFiles = deployment_helper_1.getManifestFiles(TaskInputParameters.manifests);
|
||||
if (blue_green_helper_1.isIngressRoute()) {
|
||||
yield ingress_blue_green_helper_1.rejectBlueGreenIngress(kubectl, inputManifestFiles);
|
||||
}
|
||||
else if (blue_green_helper_1.isSMIRoute()) {
|
||||
yield smi_blue_green_helper_1.rejectBlueGreenSMI(kubectl, inputManifestFiles);
|
||||
}
|
||||
else {
|
||||
yield service_blue_green_helper_1.rejectBlueGreenService(kubectl, inputManifestFiles);
|
||||
}
|
||||
});
|
||||
}
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.reject = void 0;
|
||||
const core = require("@actions/core");
|
||||
const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper");
|
||||
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
|
||||
const kubectl_object_model_1 = require("../kubectl-object-model");
|
||||
const utils = require("../utilities/manifest-utilities");
|
||||
const TaskInputParameters = require("../input-parameters");
|
||||
const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
|
||||
const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
|
||||
const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
|
||||
const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
|
||||
const deployment_helper_1 = require("../utilities/strategy-helpers/deployment-helper");
|
||||
function reject() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
|
||||
if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
|
||||
yield rejectCanary(kubectl);
|
||||
}
|
||||
else if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
|
||||
yield rejectBlueGreen(kubectl);
|
||||
}
|
||||
else {
|
||||
core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
|
||||
throw ('InvalidDeletetActionDeploymentStrategy');
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.reject = reject;
|
||||
function rejectCanary(kubectl) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let includeServices = false;
|
||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||
core.debug('Reject deployment with SMI canary strategy');
|
||||
includeServices = true;
|
||||
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests);
|
||||
}
|
||||
core.debug('Deployment strategy selected is Canary. Deleting baseline and canary workloads.');
|
||||
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
|
||||
});
|
||||
}
|
||||
function rejectBlueGreen(kubectl) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let inputManifestFiles = deployment_helper_1.getManifestFiles(TaskInputParameters.manifests);
|
||||
if (blue_green_helper_1.isIngressRoute()) {
|
||||
yield ingress_blue_green_helper_1.rejectBlueGreenIngress(kubectl, inputManifestFiles);
|
||||
}
|
||||
else if (blue_green_helper_1.isSMIRoute()) {
|
||||
yield smi_blue_green_helper_1.rejectBlueGreenSMI(kubectl, inputManifestFiles);
|
||||
}
|
||||
else {
|
||||
yield service_blue_green_helper_1.rejectBlueGreenService(kubectl, inputManifestFiles);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+54
-39
@@ -1,39 +1,54 @@
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.workflowAnnotations = exports.workloadTypesWithRolloutStatus = exports.workloadTypes = exports.deploymentTypes = exports.ServiceTypes = exports.DiscoveryAndLoadBalancerResource = exports.KubernetesWorkload = void 0;
|
||||
class KubernetesWorkload {
|
||||
}
|
||||
exports.KubernetesWorkload = KubernetesWorkload;
|
||||
KubernetesWorkload.pod = 'Pod';
|
||||
KubernetesWorkload.replicaset = 'Replicaset';
|
||||
KubernetesWorkload.deployment = 'Deployment';
|
||||
KubernetesWorkload.statefulSet = 'StatefulSet';
|
||||
KubernetesWorkload.daemonSet = 'DaemonSet';
|
||||
KubernetesWorkload.job = 'job';
|
||||
KubernetesWorkload.cronjob = 'cronjob';
|
||||
class DiscoveryAndLoadBalancerResource {
|
||||
}
|
||||
exports.DiscoveryAndLoadBalancerResource = DiscoveryAndLoadBalancerResource;
|
||||
DiscoveryAndLoadBalancerResource.service = 'service';
|
||||
DiscoveryAndLoadBalancerResource.ingress = 'ingress';
|
||||
class ServiceTypes {
|
||||
}
|
||||
exports.ServiceTypes = ServiceTypes;
|
||||
ServiceTypes.loadBalancer = 'LoadBalancer';
|
||||
ServiceTypes.nodePort = 'NodePort';
|
||||
ServiceTypes.clusterIP = 'ClusterIP';
|
||||
exports.deploymentTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset'];
|
||||
exports.workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
|
||||
exports.workloadTypesWithRolloutStatus = ['deployment', 'daemonset', 'statefulset'];
|
||||
exports.workflowAnnotations = [
|
||||
`run=${process.env['GITHUB_RUN_ID']}`,
|
||||
`repository=${process.env['GITHUB_REPOSITORY']}`,
|
||||
`workflow=${process.env['GITHUB_WORKFLOW']}`,
|
||||
`jobName=${process.env['GITHUB_JOB']}`,
|
||||
`createdBy=${process.env['GITHUB_ACTOR']}`,
|
||||
`runUri=https://github.com/${process.env['GITHUB_REPOSITORY']}/actions/runs/${process.env['GITHUB_RUN_ID']}`,
|
||||
`commit=${process.env['GITHUB_SHA']}`,
|
||||
`branch=${process.env['GITHUB_REF']}`,
|
||||
`deployTimestamp=${Date.now()}`,
|
||||
`provider=GitHub`
|
||||
];
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getWorkflowAnnotationKeyLabel = exports.getWorkflowAnnotationsJson = exports.workloadTypesWithRolloutStatus = exports.workloadTypes = exports.deploymentTypes = exports.ServiceTypes = exports.DiscoveryAndLoadBalancerResource = exports.KubernetesWorkload = void 0;
|
||||
class KubernetesWorkload {
|
||||
}
|
||||
exports.KubernetesWorkload = KubernetesWorkload;
|
||||
KubernetesWorkload.pod = 'Pod';
|
||||
KubernetesWorkload.replicaset = 'Replicaset';
|
||||
KubernetesWorkload.deployment = 'Deployment';
|
||||
KubernetesWorkload.statefulSet = 'StatefulSet';
|
||||
KubernetesWorkload.daemonSet = 'DaemonSet';
|
||||
KubernetesWorkload.job = 'job';
|
||||
KubernetesWorkload.cronjob = 'cronjob';
|
||||
class DiscoveryAndLoadBalancerResource {
|
||||
}
|
||||
exports.DiscoveryAndLoadBalancerResource = DiscoveryAndLoadBalancerResource;
|
||||
DiscoveryAndLoadBalancerResource.service = 'service';
|
||||
DiscoveryAndLoadBalancerResource.ingress = 'ingress';
|
||||
class ServiceTypes {
|
||||
}
|
||||
exports.ServiceTypes = ServiceTypes;
|
||||
ServiceTypes.loadBalancer = 'LoadBalancer';
|
||||
ServiceTypes.nodePort = 'NodePort';
|
||||
ServiceTypes.clusterIP = 'ClusterIP';
|
||||
exports.deploymentTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset'];
|
||||
exports.workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
|
||||
exports.workloadTypesWithRolloutStatus = ['deployment', 'daemonset', 'statefulset'];
|
||||
function getWorkflowAnnotationsJson(lastSuccessRunSha, workflowFilePath, deploymentConfig) {
|
||||
let annotationObject = {};
|
||||
annotationObject["run"] = process.env.GITHUB_RUN_ID;
|
||||
annotationObject["repository"] = process.env.GITHUB_REPOSITORY;
|
||||
annotationObject["workflow"] = process.env.GITHUB_WORKFLOW;
|
||||
annotationObject["workflowFileName"] = workflowFilePath.replace(".github/workflows/", "");
|
||||
annotationObject["jobName"] = process.env.GITHUB_JOB;
|
||||
annotationObject["createdBy"] = process.env.GITHUB_ACTOR;
|
||||
annotationObject["runUri"] = `https://github.com/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;
|
||||
annotationObject["commit"] = process.env.GITHUB_SHA;
|
||||
annotationObject["lastSuccessRunCommit"] = lastSuccessRunSha;
|
||||
annotationObject["branch"] = process.env.GITHUB_REF;
|
||||
annotationObject["deployTimestamp"] = Date.now();
|
||||
annotationObject["dockerfilePaths"] = deploymentConfig.dockerfilePaths;
|
||||
annotationObject["manifestsPaths"] = deploymentConfig.manifestFilePaths;
|
||||
annotationObject["helmChartPaths"] = deploymentConfig.helmChartFilePaths;
|
||||
annotationObject["provider"] = "GitHub";
|
||||
return JSON.stringify(annotationObject);
|
||||
}
|
||||
exports.getWorkflowAnnotationsJson = getWorkflowAnnotationsJson;
|
||||
function getWorkflowAnnotationKeyLabel(workflowFilePath) {
|
||||
const hashKey = require("crypto").createHash("MD5")
|
||||
.update(`${process.env.GITHUB_REPOSITORY}/${workflowFilePath}`)
|
||||
.digest("hex");
|
||||
return `githubWorkflow_${hashKey}`;
|
||||
}
|
||||
exports.getWorkflowAnnotationKeyLabel = getWorkflowAnnotationKeyLabel;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DockerExec = void 0;
|
||||
const tool_runner_1 = require("./utilities/tool-runner");
|
||||
class DockerExec {
|
||||
constructor(dockerPath) {
|
||||
this.dockerPath = dockerPath;
|
||||
}
|
||||
;
|
||||
pull(image, args, silent) {
|
||||
args = ['pull', image, ...args];
|
||||
let result = this.execute(args, silent);
|
||||
if (result.stderr != '' && result.code != 0) {
|
||||
throw new Error(`docker images pull failed with: ${result.error}`);
|
||||
}
|
||||
}
|
||||
inspect(image, args, silent) {
|
||||
args = ['inspect', image, ...args];
|
||||
let result = this.execute(args, silent);
|
||||
if (result.stderr != '' && result.code != 0) {
|
||||
throw new Error(`docker inspect call failed with: ${result.error}`);
|
||||
}
|
||||
return result.stdout;
|
||||
}
|
||||
execute(args, silent) {
|
||||
const command = new tool_runner_1.ToolRunner(this.dockerPath);
|
||||
command.arg(args);
|
||||
return command.execSync({ silent: !!silent });
|
||||
}
|
||||
}
|
||||
exports.DockerExec = DockerExec;
|
||||
@@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.GitHubClient = void 0;
|
||||
const core = require("@actions/core");
|
||||
const httpClient_1 = require("./utilities/httpClient");
|
||||
class GitHubClient {
|
||||
constructor(repository, token) {
|
||||
this._repository = repository;
|
||||
this._token = token;
|
||||
}
|
||||
getWorkflows() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const getWorkflowFileNameUrl = `https://api.github.com/repos/${this._repository}/actions/workflows`;
|
||||
const webRequest = new httpClient_1.WebRequest();
|
||||
webRequest.method = "GET";
|
||||
webRequest.uri = getWorkflowFileNameUrl;
|
||||
webRequest.headers = {
|
||||
Authorization: `Bearer ${this._token}`
|
||||
};
|
||||
core.debug(`Getting workflows for repo: ${this._repository}`);
|
||||
const response = yield httpClient_1.sendRequest(webRequest);
|
||||
return Promise.resolve(response);
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.GitHubClient = GitHubClient;
|
||||
+57
-53
@@ -1,53 +1,57 @@
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.forceDeployment = exports.args = exports.baselineAndCanaryReplicas = exports.versionSwitchBuffer = exports.routeMethod = exports.trafficSplitMethod = exports.deploymentStrategy = exports.canaryPercentage = exports.manifests = exports.imagePullSecrets = exports.containers = exports.namespace = void 0;
|
||||
const core = require("@actions/core");
|
||||
exports.namespace = core.getInput('namespace');
|
||||
exports.containers = core.getInput('images').split('\n');
|
||||
exports.imagePullSecrets = core.getInput('imagepullsecrets').split('\n').filter(secret => secret.trim().length > 0);
|
||||
exports.manifests = core.getInput('manifests').split('\n');
|
||||
exports.canaryPercentage = core.getInput('percentage');
|
||||
exports.deploymentStrategy = core.getInput('strategy');
|
||||
exports.trafficSplitMethod = core.getInput('traffic-split-method');
|
||||
exports.routeMethod = core.getInput('route-method');
|
||||
exports.versionSwitchBuffer = core.getInput('version-switch-buffer');
|
||||
exports.baselineAndCanaryReplicas = core.getInput('baseline-and-canary-replicas');
|
||||
exports.args = core.getInput('arguments');
|
||||
exports.forceDeployment = core.getInput('force').toLowerCase() == 'true';
|
||||
if (!exports.namespace) {
|
||||
core.debug('Namespace was not supplied; using "default" namespace instead.');
|
||||
exports.namespace = 'default';
|
||||
}
|
||||
try {
|
||||
const pe = parseInt(exports.canaryPercentage);
|
||||
if (pe < 0 || pe > 100) {
|
||||
core.setFailed('A valid percentage value is between 0 and 100');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.setFailed("Enter a valid 'percentage' integer value ");
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
const pe = parseInt(exports.baselineAndCanaryReplicas);
|
||||
if (pe < 0 || pe > 100) {
|
||||
core.setFailed('A valid baseline-and-canary-replicas value is between 0 and 100');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.setFailed("Enter a valid 'baseline-and-canary-replicas' integer value");
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
const pe = parseInt(exports.versionSwitchBuffer);
|
||||
if (pe < 0 || pe > 300) {
|
||||
core.setFailed('Invalid buffer time, valid version-switch-buffer is a value more than or equal to 0 and lesser than or equal 300');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.setFailed("Enter a valid 'version-switch-buffer' integer value");
|
||||
process.exit(1);
|
||||
}
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.githubToken = exports.forceDeployment = exports.args = exports.baselineAndCanaryReplicas = exports.versionSwitchBuffer = exports.routeMethod = exports.trafficSplitMethod = exports.deploymentStrategy = exports.canaryPercentage = exports.manifests = exports.imagePullSecrets = exports.containers = exports.namespace = void 0;
|
||||
const core = require("@actions/core");
|
||||
exports.namespace = core.getInput('namespace');
|
||||
exports.containers = core.getInput('images').split('\n');
|
||||
exports.imagePullSecrets = core.getInput('imagepullsecrets').split('\n').filter(secret => secret.trim().length > 0);
|
||||
exports.manifests = core.getInput('manifests').split(/[\n,;]+/).filter(manifest => manifest.trim().length > 0);
|
||||
exports.canaryPercentage = core.getInput('percentage');
|
||||
exports.deploymentStrategy = core.getInput('strategy');
|
||||
exports.trafficSplitMethod = core.getInput('traffic-split-method');
|
||||
exports.routeMethod = core.getInput('route-method');
|
||||
exports.versionSwitchBuffer = core.getInput('version-switch-buffer');
|
||||
exports.baselineAndCanaryReplicas = core.getInput('baseline-and-canary-replicas');
|
||||
exports.args = core.getInput('arguments');
|
||||
exports.forceDeployment = core.getInput('force').toLowerCase() == 'true';
|
||||
exports.githubToken = core.getInput("token");
|
||||
if (!exports.namespace) {
|
||||
core.debug('Namespace was not supplied; using "default" namespace instead.');
|
||||
exports.namespace = 'default';
|
||||
}
|
||||
if (!exports.githubToken) {
|
||||
core.error("'token' input is not supplied. Set it to a PAT/GITHUB_TOKEN");
|
||||
}
|
||||
try {
|
||||
const pe = parseInt(exports.canaryPercentage);
|
||||
if (pe < 0 || pe > 100) {
|
||||
core.setFailed('A valid percentage value is between 0 and 100');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.setFailed("Enter a valid 'percentage' integer value ");
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
const pe = parseInt(exports.baselineAndCanaryReplicas);
|
||||
if (pe < 0 || pe > 100) {
|
||||
core.setFailed('A valid baseline-and-canary-replicas value is between 0 and 100');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.setFailed("Enter a valid 'baseline-and-canary-replicas' integer value");
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
const pe = parseInt(exports.versionSwitchBuffer);
|
||||
if (pe < 0 || pe > 300) {
|
||||
core.setFailed('Invalid buffer time, valid version-switch-buffer is a value more than or equal to 0 and lesser than or equal 300');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.setFailed("Enter a valid 'version-switch-buffer' integer value");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
+117
-114
@@ -1,114 +1,117 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Kubectl = void 0;
|
||||
const tool_runner_1 = require("./utilities/tool-runner");
|
||||
class Kubectl {
|
||||
constructor(kubectlPath, namespace, ignoreSSLErrors) {
|
||||
this.kubectlPath = kubectlPath;
|
||||
this.ignoreSSLErrors = !!ignoreSSLErrors;
|
||||
if (!!namespace) {
|
||||
this.namespace = namespace;
|
||||
}
|
||||
else {
|
||||
this.namespace = 'default';
|
||||
}
|
||||
}
|
||||
apply(configurationPaths, force) {
|
||||
let applyArgs = ['apply', '-f', this.createInlineArray(configurationPaths)];
|
||||
if (!!force) {
|
||||
console.log("force flag is on, deployment will continue even if previous deployment already exists");
|
||||
applyArgs.push('--force');
|
||||
}
|
||||
return this.execute(applyArgs);
|
||||
}
|
||||
describe(resourceType, resourceName, silent) {
|
||||
return this.execute(['describe', resourceType, resourceName], silent);
|
||||
}
|
||||
getNewReplicaSet(deployment) {
|
||||
let newReplicaSet = '';
|
||||
const result = this.describe('deployment', deployment, true);
|
||||
if (result && result.stdout) {
|
||||
const stdout = result.stdout.split('\n');
|
||||
stdout.forEach((line) => {
|
||||
if (!!line && line.toLowerCase().indexOf('newreplicaset') > -1) {
|
||||
newReplicaSet = line.substr(14).trim().split(' ')[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
return newReplicaSet;
|
||||
}
|
||||
annotate(resourceType, resourceName, annotations, overwrite) {
|
||||
let args = ['annotate', resourceType, resourceName];
|
||||
args = args.concat(annotations);
|
||||
if (!!overwrite) {
|
||||
args.push(`--overwrite`);
|
||||
}
|
||||
return this.execute(args);
|
||||
}
|
||||
annotateFiles(files, annotations, overwrite) {
|
||||
let args = ['annotate'];
|
||||
args = args.concat(['-f', this.createInlineArray(files)]);
|
||||
args = args.concat(annotations);
|
||||
if (!!overwrite) {
|
||||
args.push(`--overwrite`);
|
||||
}
|
||||
return this.execute(args);
|
||||
}
|
||||
getAllPods() {
|
||||
return this.execute(['get', 'pods', '-o', 'json'], true);
|
||||
}
|
||||
getClusterInfo() {
|
||||
return this.execute(['cluster-info'], true);
|
||||
}
|
||||
checkRolloutStatus(resourceType, name) {
|
||||
return this.execute(['rollout', 'status', resourceType + '/' + name]);
|
||||
}
|
||||
getResource(resourceType, name) {
|
||||
return this.execute(['get', resourceType + '/' + name, '-o', 'json']);
|
||||
}
|
||||
getResources(applyOutput, filterResourceTypes) {
|
||||
const outputLines = applyOutput.split('\n');
|
||||
const results = [];
|
||||
outputLines.forEach(line => {
|
||||
const words = line.split(' ');
|
||||
if (words.length > 2) {
|
||||
const resourceType = words[0].trim();
|
||||
const resourceName = JSON.parse(words[1].trim());
|
||||
if (filterResourceTypes.filter(type => !!type && resourceType.toLowerCase().startsWith(type.toLowerCase())).length > 0) {
|
||||
results.push({
|
||||
type: resourceType,
|
||||
name: resourceName
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
return results;
|
||||
}
|
||||
executeCommand(customCommand, args) {
|
||||
if (!customCommand)
|
||||
throw new Error('NullCommandForKubectl');
|
||||
return args ? this.execute([customCommand, args]) : this.execute([customCommand]);
|
||||
}
|
||||
delete(args) {
|
||||
if (typeof args === 'string')
|
||||
return this.execute(['delete', args]);
|
||||
else
|
||||
return this.execute(['delete'].concat(args));
|
||||
}
|
||||
execute(args, silent) {
|
||||
if (this.ignoreSSLErrors) {
|
||||
args.push('--insecure-skip-tls-verify');
|
||||
}
|
||||
args = args.concat(['--namespace', this.namespace]);
|
||||
const command = new tool_runner_1.ToolRunner(this.kubectlPath);
|
||||
command.arg(args);
|
||||
return command.execSync({ silent: !!silent });
|
||||
}
|
||||
createInlineArray(str) {
|
||||
if (typeof str === 'string') {
|
||||
return str;
|
||||
}
|
||||
return str.join(',');
|
||||
}
|
||||
}
|
||||
exports.Kubectl = Kubectl;
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Kubectl = void 0;
|
||||
const tool_runner_1 = require("./utilities/tool-runner");
|
||||
class Kubectl {
|
||||
constructor(kubectlPath, namespace, ignoreSSLErrors) {
|
||||
this.kubectlPath = kubectlPath;
|
||||
this.ignoreSSLErrors = !!ignoreSSLErrors;
|
||||
if (!!namespace) {
|
||||
this.namespace = namespace;
|
||||
}
|
||||
else {
|
||||
this.namespace = 'default';
|
||||
}
|
||||
}
|
||||
apply(configurationPaths, force) {
|
||||
let applyArgs = ['apply', '-f', this.createInlineArray(configurationPaths)];
|
||||
if (!!force) {
|
||||
console.log("force flag is on, deployment will continue even if previous deployment already exists");
|
||||
applyArgs.push('--force');
|
||||
}
|
||||
return this.execute(applyArgs);
|
||||
}
|
||||
describe(resourceType, resourceName, silent) {
|
||||
return this.execute(['describe', resourceType, resourceName], silent);
|
||||
}
|
||||
getNewReplicaSet(deployment) {
|
||||
let newReplicaSet = '';
|
||||
const result = this.describe('deployment', deployment, true);
|
||||
if (result && result.stdout) {
|
||||
const stdout = result.stdout.split('\n');
|
||||
stdout.forEach((line) => {
|
||||
if (!!line && line.toLowerCase().indexOf('newreplicaset') > -1) {
|
||||
newReplicaSet = line.substr(14).trim().split(' ')[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
return newReplicaSet;
|
||||
}
|
||||
annotate(resourceType, resourceName, annotation) {
|
||||
let args = ['annotate', resourceType, resourceName];
|
||||
args.push(annotation);
|
||||
args.push(`--overwrite`);
|
||||
return this.execute(args);
|
||||
}
|
||||
annotateFiles(files, annotation) {
|
||||
let args = ['annotate'];
|
||||
args = args.concat(['-f', this.createInlineArray(files)]);
|
||||
args.push(annotation);
|
||||
args.push(`--overwrite`);
|
||||
return this.execute(args);
|
||||
}
|
||||
labelFiles(files, labels) {
|
||||
let args = ['label'];
|
||||
args = args.concat(['-f', this.createInlineArray(files)]);
|
||||
args = args.concat(labels);
|
||||
args.push(`--overwrite`);
|
||||
return this.execute(args);
|
||||
}
|
||||
getAllPods() {
|
||||
return this.execute(['get', 'pods', '-o', 'json'], true);
|
||||
}
|
||||
getClusterInfo() {
|
||||
return this.execute(['cluster-info'], true);
|
||||
}
|
||||
checkRolloutStatus(resourceType, name) {
|
||||
return this.execute(['rollout', 'status', resourceType + '/' + name]);
|
||||
}
|
||||
getResource(resourceType, name) {
|
||||
return this.execute(['get', resourceType + '/' + name, '-o', 'json']);
|
||||
}
|
||||
getResources(applyOutput, filterResourceTypes) {
|
||||
const outputLines = applyOutput.split('\n');
|
||||
const results = [];
|
||||
outputLines.forEach(line => {
|
||||
const words = line.split(' ');
|
||||
if (words.length > 2) {
|
||||
const resourceType = words[0].trim();
|
||||
const resourceName = JSON.parse(words[1].trim());
|
||||
if (filterResourceTypes.filter(type => !!type && resourceType.toLowerCase().startsWith(type.toLowerCase())).length > 0) {
|
||||
results.push({
|
||||
type: resourceType,
|
||||
name: resourceName
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
return results;
|
||||
}
|
||||
executeCommand(customCommand, args) {
|
||||
if (!customCommand)
|
||||
throw new Error('NullCommandForKubectl');
|
||||
return args ? this.execute([customCommand, args]) : this.execute([customCommand]);
|
||||
}
|
||||
delete(args) {
|
||||
if (typeof args === 'string')
|
||||
return this.execute(['delete', args]);
|
||||
else
|
||||
return this.execute(['delete'].concat(args));
|
||||
}
|
||||
execute(args, silent) {
|
||||
if (this.ignoreSSLErrors) {
|
||||
args.push('--insecure-skip-tls-verify');
|
||||
}
|
||||
args = args.concat(['--namespace', this.namespace]);
|
||||
const command = new tool_runner_1.ToolRunner(this.kubectlPath);
|
||||
command.arg(args);
|
||||
return command.execSync({ silent: !!silent });
|
||||
}
|
||||
createInlineArray(str) {
|
||||
if (typeof str === 'string') {
|
||||
return str;
|
||||
}
|
||||
return str.join(',');
|
||||
}
|
||||
}
|
||||
exports.Kubectl = Kubectl;
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const util = require("util");
|
||||
const fs = require("fs");
|
||||
const toolCache = require("@actions/tool-cache");
|
||||
const core = require("@actions/core");
|
||||
const kubectlToolName = 'kubectl';
|
||||
const stableKubectlVersion = 'v1.15.0';
|
||||
const stableVersionUrl = 'https://storage.googleapis.com/kubernetes-release/release/stable.txt';
|
||||
function getExecutableExtension() {
|
||||
if (os.type().match(/^Win/)) {
|
||||
return '.exe';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
function getkubectlDownloadURL(version) {
|
||||
switch (os.type()) {
|
||||
case 'Linux':
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/amd64/kubectl', version);
|
||||
case 'Darwin':
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/amd64/kubectl', version);
|
||||
case 'Windows_NT':
|
||||
default:
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/amd64/kubectl.exe', version);
|
||||
}
|
||||
}
|
||||
function getStableKubectlVersion() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return toolCache.downloadTool(stableVersionUrl).then((downloadPath) => {
|
||||
let version = fs.readFileSync(downloadPath, 'utf8').toString().trim();
|
||||
if (!version) {
|
||||
version = stableKubectlVersion;
|
||||
}
|
||||
return version;
|
||||
}, (error) => {
|
||||
core.debug(error);
|
||||
core.warning('GetStableVersionFailed');
|
||||
return stableKubectlVersion;
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.getStableKubectlVersion = getStableKubectlVersion;
|
||||
function downloadKubectl(version) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let cachedToolpath = toolCache.find(kubectlToolName, version);
|
||||
let kubectlDownloadPath = '';
|
||||
if (!cachedToolpath) {
|
||||
try {
|
||||
kubectlDownloadPath = yield toolCache.downloadTool(getkubectlDownloadURL(version));
|
||||
}
|
||||
catch (exception) {
|
||||
throw new Error('DownloadKubectlFailed');
|
||||
}
|
||||
cachedToolpath = yield toolCache.cacheFile(kubectlDownloadPath, kubectlToolName + getExecutableExtension(), kubectlToolName, version);
|
||||
}
|
||||
const kubectlPath = path.join(cachedToolpath, kubectlToolName + getExecutableExtension());
|
||||
fs.chmodSync(kubectlPath, '777');
|
||||
return kubectlPath;
|
||||
});
|
||||
}
|
||||
exports.downloadKubectl = downloadKubectl;
|
||||
function getTrafficSplitAPIVersion(kubectl) {
|
||||
const result = kubectl.executeCommand('api-versions');
|
||||
const trafficSplitAPIVersion = result.stdout.split('\n').find(version => version.startsWith('split.smi-spec.io'));
|
||||
if (trafficSplitAPIVersion == null || typeof trafficSplitAPIVersion == 'undefined') {
|
||||
throw new Error('UnableToCreateTrafficSplitManifestFile');
|
||||
}
|
||||
return trafficSplitAPIVersion;
|
||||
}
|
||||
exports.getTrafficSplitAPIVersion = getTrafficSplitAPIVersion;
|
||||
+96
-91
@@ -1,91 +1,96 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.run = void 0;
|
||||
const core = require("@actions/core");
|
||||
const io = require("@actions/io");
|
||||
const path = require("path");
|
||||
const toolCache = require("@actions/tool-cache");
|
||||
const kubectl_util_1 = require("./utilities/kubectl-util");
|
||||
const utility_1 = require("./utilities/utility");
|
||||
const kubectl_object_model_1 = require("./kubectl-object-model");
|
||||
const deployment_helper_1 = require("./utilities/strategy-helpers/deployment-helper");
|
||||
const promote_1 = require("./actions/promote");
|
||||
const reject_1 = require("./actions/reject");
|
||||
let kubectlPath = "";
|
||||
function setKubectlPath() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (core.getInput('kubectl-version')) {
|
||||
const version = core.getInput('kubectl-version');
|
||||
kubectlPath = toolCache.find('kubectl', version);
|
||||
if (!kubectlPath) {
|
||||
kubectlPath = yield installKubectl(version);
|
||||
}
|
||||
}
|
||||
else {
|
||||
kubectlPath = yield io.which('kubectl', false);
|
||||
if (!kubectlPath) {
|
||||
const allVersions = toolCache.findAllVersions('kubectl');
|
||||
kubectlPath = allVersions.length > 0 ? toolCache.find('kubectl', allVersions[0]) : '';
|
||||
if (!kubectlPath) {
|
||||
throw new Error('Kubectl is not installed, either add install-kubectl action or provide "kubectl-version" input to download kubectl');
|
||||
}
|
||||
kubectlPath = path.join(kubectlPath, `kubectl${utility_1.getExecutableExtension()}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function installKubectl(version) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (utility_1.isEqual(version, 'latest')) {
|
||||
version = yield kubectl_util_1.getStableKubectlVersion();
|
||||
}
|
||||
return yield kubectl_util_1.downloadKubectl(version);
|
||||
});
|
||||
}
|
||||
function checkClusterContext() {
|
||||
if (!process.env["KUBECONFIG"]) {
|
||||
throw new Error('Cluster context not set. Use k8ssetcontext action to set cluster context');
|
||||
}
|
||||
}
|
||||
function run() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
checkClusterContext();
|
||||
yield setKubectlPath();
|
||||
let manifestsInput = core.getInput('manifests');
|
||||
if (!manifestsInput) {
|
||||
core.setFailed('No manifests supplied to deploy');
|
||||
return;
|
||||
}
|
||||
let namespace = core.getInput('namespace');
|
||||
if (!namespace) {
|
||||
namespace = 'default';
|
||||
}
|
||||
let action = core.getInput('action');
|
||||
let manifests = manifestsInput.split('\n');
|
||||
if (action === 'deploy') {
|
||||
let strategy = core.getInput('strategy');
|
||||
console.log("strategy: ", strategy);
|
||||
yield deployment_helper_1.deploy(new kubectl_object_model_1.Kubectl(kubectlPath, namespace), manifests, strategy);
|
||||
}
|
||||
else if (action === 'promote') {
|
||||
yield promote_1.promote();
|
||||
}
|
||||
else if (action === 'reject') {
|
||||
yield reject_1.reject();
|
||||
}
|
||||
else {
|
||||
core.setFailed('Not a valid action. The allowed actions are deploy, promote, reject');
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.run = run;
|
||||
run().catch(core.setFailed);
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.run = void 0;
|
||||
const core = require("@actions/core");
|
||||
const io = require("@actions/io");
|
||||
const path = require("path");
|
||||
const toolCache = require("@actions/tool-cache");
|
||||
const kubectl_util_1 = require("./utilities/kubectl-util");
|
||||
const utility_1 = require("./utilities/utility");
|
||||
const kubectl_object_model_1 = require("./kubectl-object-model");
|
||||
const deployment_helper_1 = require("./utilities/strategy-helpers/deployment-helper");
|
||||
const promote_1 = require("./actions/promote");
|
||||
const reject_1 = require("./actions/reject");
|
||||
let kubectlPath = "";
|
||||
function setKubectlPath() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (core.getInput('kubectl-version')) {
|
||||
const version = core.getInput('kubectl-version');
|
||||
kubectlPath = toolCache.find('kubectl', version);
|
||||
if (!kubectlPath) {
|
||||
kubectlPath = yield installKubectl(version);
|
||||
}
|
||||
}
|
||||
else {
|
||||
kubectlPath = yield io.which('kubectl', false);
|
||||
if (!kubectlPath) {
|
||||
const allVersions = toolCache.findAllVersions('kubectl');
|
||||
kubectlPath = allVersions.length > 0 ? toolCache.find('kubectl', allVersions[0]) : '';
|
||||
if (!kubectlPath) {
|
||||
throw new Error('Kubectl is not installed, either add install-kubectl action or provide "kubectl-version" input to download kubectl');
|
||||
}
|
||||
kubectlPath = path.join(kubectlPath, `kubectl${utility_1.getExecutableExtension()}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function installKubectl(version) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (utility_1.isEqual(version, 'latest')) {
|
||||
version = yield kubectl_util_1.getStableKubectlVersion();
|
||||
}
|
||||
return yield kubectl_util_1.downloadKubectl(version);
|
||||
});
|
||||
}
|
||||
function checkClusterContext() {
|
||||
if (!process.env["KUBECONFIG"]) {
|
||||
core.warning('KUBECONFIG env is not explicitly set. Ensure cluster context is set by using k8s-set-context / aks-set-context action.');
|
||||
}
|
||||
}
|
||||
function run() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
checkClusterContext();
|
||||
yield setKubectlPath();
|
||||
let manifestsInput = core.getInput('manifests');
|
||||
if (!manifestsInput) {
|
||||
core.setFailed('No manifests supplied to deploy');
|
||||
return;
|
||||
}
|
||||
let namespace = core.getInput('namespace');
|
||||
if (!namespace) {
|
||||
namespace = 'default';
|
||||
}
|
||||
let action = core.getInput('action');
|
||||
let manifests = manifestsInput.split(/[\n,;]+/).filter(manifest => manifest.trim().length > 0);
|
||||
if (manifests.length > 0) {
|
||||
manifests = manifests.map(manifest => {
|
||||
return manifest.trim();
|
||||
});
|
||||
}
|
||||
if (action === 'deploy') {
|
||||
let strategy = core.getInput('strategy');
|
||||
console.log("strategy: ", strategy);
|
||||
yield deployment_helper_1.deploy(new kubectl_object_model_1.Kubectl(kubectlPath, namespace), manifests, strategy);
|
||||
}
|
||||
else if (action === 'promote') {
|
||||
yield promote_1.promote();
|
||||
}
|
||||
else if (action === 'reject') {
|
||||
yield reject_1.reject();
|
||||
}
|
||||
else {
|
||||
core.setFailed('Not a valid action. The allowed actions are deploy, promote, reject');
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.run = run;
|
||||
run().catch(core.setFailed);
|
||||
|
||||
@@ -1,78 +1,78 @@
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.writeManifestToFile = exports.writeObjectsToFile = exports.assertFileExists = exports.ensureDirExists = exports.getNewUserDirPath = exports.getTempDirectory = void 0;
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const core = require("@actions/core");
|
||||
const os = require("os");
|
||||
function getTempDirectory() {
|
||||
return process.env['runner.tempDirectory'] || os.tmpdir();
|
||||
}
|
||||
exports.getTempDirectory = getTempDirectory;
|
||||
function getNewUserDirPath() {
|
||||
let userDir = path.join(getTempDirectory(), 'kubectlTask');
|
||||
ensureDirExists(userDir);
|
||||
userDir = path.join(userDir, getCurrentTime().toString());
|
||||
ensureDirExists(userDir);
|
||||
return userDir;
|
||||
}
|
||||
exports.getNewUserDirPath = getNewUserDirPath;
|
||||
function ensureDirExists(dirPath) {
|
||||
if (!fs.existsSync(dirPath)) {
|
||||
fs.mkdirSync(dirPath);
|
||||
}
|
||||
}
|
||||
exports.ensureDirExists = ensureDirExists;
|
||||
function assertFileExists(path) {
|
||||
if (!fs.existsSync(path)) {
|
||||
core.error(`FileNotFoundException : ${path}`);
|
||||
throw new Error(`FileNotFoundException: ${path}`);
|
||||
}
|
||||
}
|
||||
exports.assertFileExists = assertFileExists;
|
||||
function writeObjectsToFile(inputObjects) {
|
||||
const newFilePaths = [];
|
||||
if (!!inputObjects) {
|
||||
inputObjects.forEach((inputObject) => {
|
||||
try {
|
||||
const inputObjectString = JSON.stringify(inputObject);
|
||||
if (!!inputObject.kind && !!inputObject.metadata && !!inputObject.metadata.name) {
|
||||
const fileName = getManifestFileName(inputObject.kind, inputObject.metadata.name);
|
||||
fs.writeFileSync(path.join(fileName), inputObjectString);
|
||||
newFilePaths.push(fileName);
|
||||
}
|
||||
else {
|
||||
core.debug('Input object is not proper K8s resource object. Object: ' + inputObjectString);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug('Exception occurred while writing object to file : ' + inputObject + ' . Exception: ' + ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
return newFilePaths;
|
||||
}
|
||||
exports.writeObjectsToFile = writeObjectsToFile;
|
||||
function writeManifestToFile(inputObjectString, kind, name) {
|
||||
if (inputObjectString) {
|
||||
try {
|
||||
const fileName = getManifestFileName(kind, name);
|
||||
fs.writeFileSync(path.join(fileName), inputObjectString);
|
||||
return fileName;
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug('Exception occurred while writing object to file : ' + inputObjectString + ' . Exception: ' + ex);
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
exports.writeManifestToFile = writeManifestToFile;
|
||||
function getManifestFileName(kind, name) {
|
||||
const filePath = kind + '_' + name + '_' + getCurrentTime().toString();
|
||||
const tempDirectory = getTempDirectory();
|
||||
const fileName = path.join(tempDirectory, path.basename(filePath));
|
||||
return fileName;
|
||||
}
|
||||
function getCurrentTime() {
|
||||
return new Date().getTime();
|
||||
}
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.writeManifestToFile = exports.writeObjectsToFile = exports.assertFileExists = exports.ensureDirExists = exports.getNewUserDirPath = exports.getTempDirectory = void 0;
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const core = require("@actions/core");
|
||||
const os = require("os");
|
||||
function getTempDirectory() {
|
||||
return process.env['runner.tempDirectory'] || os.tmpdir();
|
||||
}
|
||||
exports.getTempDirectory = getTempDirectory;
|
||||
function getNewUserDirPath() {
|
||||
let userDir = path.join(getTempDirectory(), 'kubectlTask');
|
||||
ensureDirExists(userDir);
|
||||
userDir = path.join(userDir, getCurrentTime().toString());
|
||||
ensureDirExists(userDir);
|
||||
return userDir;
|
||||
}
|
||||
exports.getNewUserDirPath = getNewUserDirPath;
|
||||
function ensureDirExists(dirPath) {
|
||||
if (!fs.existsSync(dirPath)) {
|
||||
fs.mkdirSync(dirPath);
|
||||
}
|
||||
}
|
||||
exports.ensureDirExists = ensureDirExists;
|
||||
function assertFileExists(path) {
|
||||
if (!fs.existsSync(path)) {
|
||||
core.error(`FileNotFoundException : ${path}`);
|
||||
throw new Error(`FileNotFoundException: ${path}`);
|
||||
}
|
||||
}
|
||||
exports.assertFileExists = assertFileExists;
|
||||
function writeObjectsToFile(inputObjects) {
|
||||
const newFilePaths = [];
|
||||
if (!!inputObjects) {
|
||||
inputObjects.forEach((inputObject) => {
|
||||
try {
|
||||
const inputObjectString = JSON.stringify(inputObject);
|
||||
if (!!inputObject.kind && !!inputObject.metadata && !!inputObject.metadata.name) {
|
||||
const fileName = getManifestFileName(inputObject.kind, inputObject.metadata.name);
|
||||
fs.writeFileSync(path.join(fileName), inputObjectString);
|
||||
newFilePaths.push(fileName);
|
||||
}
|
||||
else {
|
||||
core.debug('Input object is not proper K8s resource object. Object: ' + inputObjectString);
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug('Exception occurred while writing object to file : ' + inputObject + ' . Exception: ' + ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
return newFilePaths;
|
||||
}
|
||||
exports.writeObjectsToFile = writeObjectsToFile;
|
||||
function writeManifestToFile(inputObjectString, kind, name) {
|
||||
if (inputObjectString) {
|
||||
try {
|
||||
const fileName = getManifestFileName(kind, name);
|
||||
fs.writeFileSync(path.join(fileName), inputObjectString);
|
||||
return fileName;
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug('Exception occurred while writing object to file : ' + inputObjectString + ' . Exception: ' + ex);
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
exports.writeManifestToFile = writeManifestToFile;
|
||||
function getManifestFileName(kind, name) {
|
||||
const filePath = kind + '_' + name + '_' + getCurrentTime().toString();
|
||||
const tempDirectory = getTempDirectory();
|
||||
const fileName = path.join(tempDirectory, path.basename(filePath));
|
||||
return fileName;
|
||||
}
|
||||
function getCurrentTime() {
|
||||
return new Date().getTime();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.sleepFor = exports.sendRequest = exports.WebRequestOptions = exports.WebResponse = exports.WebRequest = exports.StatusCodes = void 0;
|
||||
// Taken from https://github.com/Azure/aks-set-context/blob/master/src/client.ts
|
||||
const util = require("util");
|
||||
const fs = require("fs");
|
||||
const httpClient = require("typed-rest-client/HttpClient");
|
||||
const core = require("@actions/core");
|
||||
var httpCallbackClient = new httpClient.HttpClient('GITHUB_RUNNER', null, {});
|
||||
var StatusCodes;
|
||||
(function (StatusCodes) {
|
||||
StatusCodes[StatusCodes["OK"] = 200] = "OK";
|
||||
StatusCodes[StatusCodes["CREATED"] = 201] = "CREATED";
|
||||
StatusCodes[StatusCodes["ACCEPTED"] = 202] = "ACCEPTED";
|
||||
StatusCodes[StatusCodes["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
|
||||
StatusCodes[StatusCodes["NOT_FOUND"] = 404] = "NOT_FOUND";
|
||||
StatusCodes[StatusCodes["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
|
||||
StatusCodes[StatusCodes["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
|
||||
})(StatusCodes = exports.StatusCodes || (exports.StatusCodes = {}));
|
||||
class WebRequest {
|
||||
}
|
||||
exports.WebRequest = WebRequest;
|
||||
class WebResponse {
|
||||
}
|
||||
exports.WebResponse = WebResponse;
|
||||
class WebRequestOptions {
|
||||
}
|
||||
exports.WebRequestOptions = WebRequestOptions;
|
||||
function sendRequest(request, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let i = 0;
|
||||
let retryCount = options && options.retryCount ? options.retryCount : 5;
|
||||
let retryIntervalInSeconds = options && options.retryIntervalInSeconds ? options.retryIntervalInSeconds : 2;
|
||||
let retriableErrorCodes = options && options.retriableErrorCodes ? options.retriableErrorCodes : ["ETIMEDOUT", "ECONNRESET", "ENOTFOUND", "ESOCKETTIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "EPIPE", "EA_AGAIN"];
|
||||
let retriableStatusCodes = options && options.retriableStatusCodes ? options.retriableStatusCodes : [408, 409, 500, 502, 503, 504];
|
||||
let timeToWait = retryIntervalInSeconds;
|
||||
while (true) {
|
||||
try {
|
||||
if (request.body && typeof (request.body) !== 'string' && !request.body["readable"]) {
|
||||
request.body = fs.createReadStream(request.body["path"]);
|
||||
}
|
||||
let response = yield sendRequestInternal(request);
|
||||
if (retriableStatusCodes.indexOf(response.statusCode) != -1 && ++i < retryCount) {
|
||||
core.debug(util.format("Encountered a retriable status code: %s. Message: '%s'.", response.statusCode, response.statusMessage));
|
||||
yield sleepFor(timeToWait);
|
||||
timeToWait = timeToWait * retryIntervalInSeconds + retryIntervalInSeconds;
|
||||
continue;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
catch (error) {
|
||||
if (retriableErrorCodes.indexOf(error.code) != -1 && ++i < retryCount) {
|
||||
core.debug(util.format("Encountered a retriable error:%s. Message: %s.", error.code, error.message));
|
||||
yield sleepFor(timeToWait);
|
||||
timeToWait = timeToWait * retryIntervalInSeconds + retryIntervalInSeconds;
|
||||
}
|
||||
else {
|
||||
if (error.code) {
|
||||
core.debug("error code =" + error.code);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.sendRequest = sendRequest;
|
||||
function sleepFor(sleepDurationInSeconds) {
|
||||
return new Promise((resolve, reject) => {
|
||||
setTimeout(resolve, sleepDurationInSeconds * 1000);
|
||||
});
|
||||
}
|
||||
exports.sleepFor = sleepFor;
|
||||
function sendRequestInternal(request) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
core.debug(util.format("[%s]%s", request.method, request.uri));
|
||||
var response = yield httpCallbackClient.request(request.method, request.uri, request.body, request.headers);
|
||||
return yield toWebResponse(response);
|
||||
});
|
||||
}
|
||||
function toWebResponse(response) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var res = new WebResponse();
|
||||
if (response) {
|
||||
res.statusCode = response.message.statusCode;
|
||||
res.statusMessage = response.message.statusMessage;
|
||||
res.headers = response.message.headers;
|
||||
var body = yield response.readBody();
|
||||
if (body) {
|
||||
try {
|
||||
res.body = JSON.parse(body);
|
||||
}
|
||||
catch (error) {
|
||||
core.debug("Could not parse response: " + JSON.stringify(error));
|
||||
core.debug("Response: " + JSON.stringify(res.body));
|
||||
res.body = body;
|
||||
}
|
||||
}
|
||||
}
|
||||
return res;
|
||||
});
|
||||
}
|
||||
@@ -16,6 +16,7 @@ const os = require("os");
|
||||
const path = require("path");
|
||||
const toolCache = require("@actions/tool-cache");
|
||||
const util = require("util");
|
||||
const httpClient_1 = require("./httpClient");
|
||||
const kubectlToolName = 'kubectl';
|
||||
const stableKubectlVersion = 'v1.15.0';
|
||||
const stableVersionUrl = 'https://storage.googleapis.com/kubernetes-release/release/stable.txt';
|
||||
@@ -26,15 +27,22 @@ function getExecutableExtension() {
|
||||
}
|
||||
return '';
|
||||
}
|
||||
function getkubectlDownloadURL(version) {
|
||||
function getKubectlArch() {
|
||||
let arch = os.arch();
|
||||
if (arch === 'x64') {
|
||||
return 'amd64';
|
||||
}
|
||||
return arch;
|
||||
}
|
||||
function getkubectlDownloadURL(version, arch) {
|
||||
switch (os.type()) {
|
||||
case 'Linux':
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/amd64/kubectl', version);
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubectl', version, arch);
|
||||
case 'Darwin':
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/amd64/kubectl', version);
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/%s/kubectl', version, arch);
|
||||
case 'Windows_NT':
|
||||
default:
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/amd64/kubectl.exe', version);
|
||||
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/%s/kubectl.exe', version, arch);
|
||||
}
|
||||
}
|
||||
exports.getkubectlDownloadURL = getkubectlDownloadURL;
|
||||
@@ -58,12 +66,18 @@ function downloadKubectl(version) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let cachedToolpath = toolCache.find(kubectlToolName, version);
|
||||
let kubectlDownloadPath = '';
|
||||
let arch = getKubectlArch();
|
||||
if (!cachedToolpath) {
|
||||
try {
|
||||
kubectlDownloadPath = yield toolCache.downloadTool(getkubectlDownloadURL(version));
|
||||
kubectlDownloadPath = yield toolCache.downloadTool(getkubectlDownloadURL(version, arch));
|
||||
}
|
||||
catch (exception) {
|
||||
throw new Error('DownloadKubectlFailed');
|
||||
if (exception instanceof toolCache.HTTPError && exception.httpStatusCode === httpClient_1.StatusCodes.NOT_FOUND) {
|
||||
throw new Error(util.format("Kubectl '%s' for '%s' arch not found.", version, arch));
|
||||
}
|
||||
else {
|
||||
throw new Error('DownloadKubectlFailed');
|
||||
}
|
||||
}
|
||||
cachedToolpath = yield toolCache.cacheFile(kubectlDownloadPath, kubectlToolName + getExecutableExtension(), kubectlToolName, version);
|
||||
}
|
||||
|
||||
@@ -1,158 +1,158 @@
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.checkPodStatus = exports.checkManifestStability = void 0;
|
||||
const core = require("@actions/core");
|
||||
const utils = require("./utility");
|
||||
const KubernetesConstants = require("../constants");
|
||||
function checkManifestStability(kubectl, resources) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let rolloutStatusHasErrors = false;
|
||||
const numberOfResources = resources.length;
|
||||
for (let i = 0; i < numberOfResources; i++) {
|
||||
const resource = resources[i];
|
||||
if (KubernetesConstants.workloadTypesWithRolloutStatus.indexOf(resource.type.toLowerCase()) >= 0) {
|
||||
try {
|
||||
var result = kubectl.checkRolloutStatus(resource.type, resource.name);
|
||||
utils.checkForErrors([result]);
|
||||
}
|
||||
catch (ex) {
|
||||
core.error(ex);
|
||||
kubectl.describe(resource.type, resource.name);
|
||||
rolloutStatusHasErrors = true;
|
||||
}
|
||||
}
|
||||
if (utils.isEqual(resource.type, KubernetesConstants.KubernetesWorkload.pod, true)) {
|
||||
try {
|
||||
yield checkPodStatus(kubectl, resource.name);
|
||||
}
|
||||
catch (ex) {
|
||||
core.warning(`CouldNotDeterminePodStatus ${JSON.stringify(ex)}`);
|
||||
kubectl.describe(resource.type, resource.name);
|
||||
}
|
||||
}
|
||||
if (utils.isEqual(resource.type, KubernetesConstants.DiscoveryAndLoadBalancerResource.service, true)) {
|
||||
try {
|
||||
const service = getService(kubectl, resource.name);
|
||||
const spec = service.spec;
|
||||
const status = service.status;
|
||||
if (utils.isEqual(spec.type, KubernetesConstants.ServiceTypes.loadBalancer, true)) {
|
||||
if (!isLoadBalancerIPAssigned(status)) {
|
||||
yield waitForServiceExternalIPAssignment(kubectl, resource.name);
|
||||
}
|
||||
else {
|
||||
console.log('ServiceExternalIP', resource.name, status.loadBalancer.ingress[0].ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.warning(`CouldNotDetermineServiceStatus of: ${resource.name} Error: ${JSON.stringify(ex)}`);
|
||||
kubectl.describe(resource.type, resource.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rolloutStatusHasErrors) {
|
||||
throw new Error('RolloutStatusTimedout');
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.checkManifestStability = checkManifestStability;
|
||||
function checkPodStatus(kubectl, podName) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const sleepTimeout = 10 * 1000; // 10 seconds
|
||||
const iterations = 60; // 60 * 10 seconds timeout = 10 minutes max timeout
|
||||
let podStatus;
|
||||
let kubectlDescribeNeeded = false;
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
yield utils.sleep(sleepTimeout);
|
||||
core.debug(`Polling for pod status: ${podName}`);
|
||||
podStatus = getPodStatus(kubectl, podName);
|
||||
if (podStatus.phase && podStatus.phase !== 'Pending' && podStatus.phase !== 'Unknown') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
podStatus = getPodStatus(kubectl, podName);
|
||||
switch (podStatus.phase) {
|
||||
case 'Succeeded':
|
||||
case 'Running':
|
||||
if (isPodReady(podStatus)) {
|
||||
console.log(`pod/${podName} is successfully rolled out`);
|
||||
}
|
||||
else {
|
||||
kubectlDescribeNeeded = true;
|
||||
}
|
||||
break;
|
||||
case 'Pending':
|
||||
if (!isPodReady(podStatus)) {
|
||||
core.warning(`pod/${podName} rollout status check timedout`);
|
||||
kubectlDescribeNeeded = true;
|
||||
}
|
||||
break;
|
||||
case 'Failed':
|
||||
core.error(`pod/${podName} rollout failed`);
|
||||
kubectlDescribeNeeded = true;
|
||||
break;
|
||||
default:
|
||||
core.warning(`pod/${podName} rollout status: ${podStatus.phase}`);
|
||||
}
|
||||
if (kubectlDescribeNeeded) {
|
||||
kubectl.describe('pod', podName);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.checkPodStatus = checkPodStatus;
|
||||
function getPodStatus(kubectl, podName) {
|
||||
const podResult = kubectl.getResource('pod', podName);
|
||||
utils.checkForErrors([podResult]);
|
||||
const podStatus = JSON.parse(podResult.stdout).status;
|
||||
core.debug(`Pod Status: ${JSON.stringify(podStatus)}`);
|
||||
return podStatus;
|
||||
}
|
||||
function isPodReady(podStatus) {
|
||||
let allContainersAreReady = true;
|
||||
podStatus.containerStatuses.forEach(container => {
|
||||
if (container.ready === false) {
|
||||
console.log(`'${container.name}' status: ${JSON.stringify(container.state)}`);
|
||||
allContainersAreReady = false;
|
||||
}
|
||||
});
|
||||
if (!allContainersAreReady) {
|
||||
core.warning('AllContainersNotInReadyState');
|
||||
}
|
||||
return allContainersAreReady;
|
||||
}
|
||||
function getService(kubectl, serviceName) {
|
||||
const serviceResult = kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.service, serviceName);
|
||||
utils.checkForErrors([serviceResult]);
|
||||
return JSON.parse(serviceResult.stdout);
|
||||
}
|
||||
function waitForServiceExternalIPAssignment(kubectl, serviceName) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const sleepTimeout = 10 * 1000; // 10 seconds
|
||||
const iterations = 18; // 18 * 10 seconds timeout = 3 minutes max timeout
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
console.log(`waitForServiceIpAssignment : ${serviceName}`);
|
||||
yield utils.sleep(sleepTimeout);
|
||||
let status = (getService(kubectl, serviceName)).status;
|
||||
if (isLoadBalancerIPAssigned(status)) {
|
||||
console.log('ServiceExternalIP', serviceName, status.loadBalancer.ingress[0].ip);
|
||||
return;
|
||||
}
|
||||
}
|
||||
core.warning(`waitForServiceIpAssignmentTimedOut ${serviceName}`);
|
||||
});
|
||||
}
|
||||
function isLoadBalancerIPAssigned(status) {
|
||||
if (status && status.loadBalancer && status.loadBalancer.ingress && status.loadBalancer.ingress.length > 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.checkPodStatus = exports.checkManifestStability = void 0;
|
||||
const core = require("@actions/core");
|
||||
const utils = require("./utility");
|
||||
const KubernetesConstants = require("../constants");
|
||||
function checkManifestStability(kubectl, resources) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let rolloutStatusHasErrors = false;
|
||||
const numberOfResources = resources.length;
|
||||
for (let i = 0; i < numberOfResources; i++) {
|
||||
const resource = resources[i];
|
||||
if (KubernetesConstants.workloadTypesWithRolloutStatus.indexOf(resource.type.toLowerCase()) >= 0) {
|
||||
try {
|
||||
var result = kubectl.checkRolloutStatus(resource.type, resource.name);
|
||||
utils.checkForErrors([result]);
|
||||
}
|
||||
catch (ex) {
|
||||
core.error(ex);
|
||||
kubectl.describe(resource.type, resource.name);
|
||||
rolloutStatusHasErrors = true;
|
||||
}
|
||||
}
|
||||
if (utils.isEqual(resource.type, KubernetesConstants.KubernetesWorkload.pod, true)) {
|
||||
try {
|
||||
yield checkPodStatus(kubectl, resource.name);
|
||||
}
|
||||
catch (ex) {
|
||||
core.warning(`CouldNotDeterminePodStatus ${JSON.stringify(ex)}`);
|
||||
kubectl.describe(resource.type, resource.name);
|
||||
}
|
||||
}
|
||||
if (utils.isEqual(resource.type, KubernetesConstants.DiscoveryAndLoadBalancerResource.service, true)) {
|
||||
try {
|
||||
const service = getService(kubectl, resource.name);
|
||||
const spec = service.spec;
|
||||
const status = service.status;
|
||||
if (utils.isEqual(spec.type, KubernetesConstants.ServiceTypes.loadBalancer, true)) {
|
||||
if (!isLoadBalancerIPAssigned(status)) {
|
||||
yield waitForServiceExternalIPAssignment(kubectl, resource.name);
|
||||
}
|
||||
else {
|
||||
console.log('ServiceExternalIP', resource.name, status.loadBalancer.ingress[0].ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.warning(`CouldNotDetermineServiceStatus of: ${resource.name} Error: ${JSON.stringify(ex)}`);
|
||||
kubectl.describe(resource.type, resource.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rolloutStatusHasErrors) {
|
||||
throw new Error('RolloutStatusTimedout');
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.checkManifestStability = checkManifestStability;
|
||||
function checkPodStatus(kubectl, podName) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const sleepTimeout = 10 * 1000; // 10 seconds
|
||||
const iterations = 60; // 60 * 10 seconds timeout = 10 minutes max timeout
|
||||
let podStatus;
|
||||
let kubectlDescribeNeeded = false;
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
yield utils.sleep(sleepTimeout);
|
||||
core.debug(`Polling for pod status: ${podName}`);
|
||||
podStatus = getPodStatus(kubectl, podName);
|
||||
if (podStatus.phase && podStatus.phase !== 'Pending' && podStatus.phase !== 'Unknown') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
podStatus = getPodStatus(kubectl, podName);
|
||||
switch (podStatus.phase) {
|
||||
case 'Succeeded':
|
||||
case 'Running':
|
||||
if (isPodReady(podStatus)) {
|
||||
console.log(`pod/${podName} is successfully rolled out`);
|
||||
}
|
||||
else {
|
||||
kubectlDescribeNeeded = true;
|
||||
}
|
||||
break;
|
||||
case 'Pending':
|
||||
if (!isPodReady(podStatus)) {
|
||||
core.warning(`pod/${podName} rollout status check timedout`);
|
||||
kubectlDescribeNeeded = true;
|
||||
}
|
||||
break;
|
||||
case 'Failed':
|
||||
core.error(`pod/${podName} rollout failed`);
|
||||
kubectlDescribeNeeded = true;
|
||||
break;
|
||||
default:
|
||||
core.warning(`pod/${podName} rollout status: ${podStatus.phase}`);
|
||||
}
|
||||
if (kubectlDescribeNeeded) {
|
||||
kubectl.describe('pod', podName);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.checkPodStatus = checkPodStatus;
|
||||
function getPodStatus(kubectl, podName) {
|
||||
const podResult = kubectl.getResource('pod', podName);
|
||||
utils.checkForErrors([podResult]);
|
||||
const podStatus = JSON.parse(podResult.stdout).status;
|
||||
core.debug(`Pod Status: ${JSON.stringify(podStatus)}`);
|
||||
return podStatus;
|
||||
}
|
||||
function isPodReady(podStatus) {
|
||||
let allContainersAreReady = true;
|
||||
podStatus.containerStatuses.forEach(container => {
|
||||
if (container.ready === false) {
|
||||
console.log(`'${container.name}' status: ${JSON.stringify(container.state)}`);
|
||||
allContainersAreReady = false;
|
||||
}
|
||||
});
|
||||
if (!allContainersAreReady) {
|
||||
core.warning('AllContainersNotInReadyState');
|
||||
}
|
||||
return allContainersAreReady;
|
||||
}
|
||||
function getService(kubectl, serviceName) {
|
||||
const serviceResult = kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.service, serviceName);
|
||||
utils.checkForErrors([serviceResult]);
|
||||
return JSON.parse(serviceResult.stdout);
|
||||
}
|
||||
function waitForServiceExternalIPAssignment(kubectl, serviceName) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const sleepTimeout = 10 * 1000; // 10 seconds
|
||||
const iterations = 18; // 18 * 10 seconds timeout = 3 minutes max timeout
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
console.log(`waitForServiceIpAssignment : ${serviceName}`);
|
||||
yield utils.sleep(sleepTimeout);
|
||||
let status = (getService(kubectl, serviceName)).status;
|
||||
if (isLoadBalancerIPAssigned(status)) {
|
||||
console.log('ServiceExternalIP', serviceName, status.loadBalancer.ingress[0].ip);
|
||||
return;
|
||||
}
|
||||
}
|
||||
core.warning(`waitForServiceIpAssignmentTimedOut ${serviceName}`);
|
||||
});
|
||||
}
|
||||
function isLoadBalancerIPAssigned(status) {
|
||||
if (status && status.loadBalancer && status.loadBalancer.ingress && status.loadBalancer.ingress.length > 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
+283
-283
@@ -1,283 +1,283 @@
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isWorkloadEntity = exports.getUpdatedManifestFiles = exports.updateImagePullSecrets = exports.substituteImageNameInSpecFile = exports.getDeleteCmdArgs = exports.createKubectlArgs = exports.getKubectl = exports.getManifestFiles = void 0;
|
||||
const core = require("@actions/core");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const path = require("path");
|
||||
const kubectlutility = require("./kubectl-util");
|
||||
const io = require("@actions/io");
|
||||
const utility_1 = require("./utility");
|
||||
const fileHelper = require("./files-helper");
|
||||
const KubernetesObjectUtility = require("./resource-object-utility");
|
||||
const TaskInputParameters = require("../input-parameters");
|
||||
function getManifestFiles(manifestFilePaths) {
|
||||
if (!manifestFilePaths) {
|
||||
core.debug('file input is not present');
|
||||
return null;
|
||||
}
|
||||
return manifestFilePaths;
|
||||
}
|
||||
exports.getManifestFiles = getManifestFiles;
|
||||
function getKubectl() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
return Promise.resolve(io.which('kubectl', true));
|
||||
}
|
||||
catch (ex) {
|
||||
return kubectlutility.downloadKubectl(yield kubectlutility.getStableKubectlVersion());
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.getKubectl = getKubectl;
|
||||
function createKubectlArgs(kinds, names) {
|
||||
let args = '';
|
||||
if (!!kinds && kinds.size > 0) {
|
||||
args = args + createInlineArray(Array.from(kinds.values()));
|
||||
}
|
||||
if (!!names && names.size > 0) {
|
||||
args = args + ' ' + Array.from(names.values()).join(' ');
|
||||
}
|
||||
return args;
|
||||
}
|
||||
exports.createKubectlArgs = createKubectlArgs;
|
||||
function getDeleteCmdArgs(argsPrefix, inputArgs) {
|
||||
let args = '';
|
||||
if (!!argsPrefix && argsPrefix.length > 0) {
|
||||
args = argsPrefix;
|
||||
}
|
||||
if (!!inputArgs && inputArgs.length > 0) {
|
||||
if (args.length > 0) {
|
||||
args = args + ' ';
|
||||
}
|
||||
args = args + inputArgs;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
exports.getDeleteCmdArgs = getDeleteCmdArgs;
|
||||
/*
|
||||
For example,
|
||||
currentString: `image: "example/example-image"`
|
||||
imageName: `example/example-image`
|
||||
imageNameWithNewTag: `example/example-image:identifiertag`
|
||||
|
||||
This substituteImageNameInSpecFile function would return
|
||||
return Value: `image: "example/example-image:identifiertag"`
|
||||
*/
|
||||
function substituteImageNameInSpecFile(currentString, imageName, imageNameWithNewTag) {
|
||||
if (currentString.indexOf(imageName) < 0) {
|
||||
core.debug(`No occurence of replacement token: ${imageName} found`);
|
||||
return currentString;
|
||||
}
|
||||
return currentString.split('\n').reduce((acc, line) => {
|
||||
const imageKeyword = line.match(/^ *image:/);
|
||||
if (imageKeyword) {
|
||||
let [currentImageName, currentImageTag] = line
|
||||
.substring(imageKeyword[0].length) // consume the line from keyword onwards
|
||||
.trim()
|
||||
.replace(/[',"]/g, '') // replace allowed quotes with nothing
|
||||
.split(':');
|
||||
if (!currentImageTag && currentImageName.indexOf(' ') > 0) {
|
||||
currentImageName = currentImageName.split(' ')[0]; // Stripping off comments
|
||||
}
|
||||
if (currentImageName === imageName) {
|
||||
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
|
||||
}
|
||||
}
|
||||
return acc + line + '\n';
|
||||
}, '');
|
||||
}
|
||||
exports.substituteImageNameInSpecFile = substituteImageNameInSpecFile;
|
||||
function createInlineArray(str) {
|
||||
if (typeof str === 'string') {
|
||||
return str;
|
||||
}
|
||||
return str.join(',');
|
||||
}
|
||||
function getImagePullSecrets(inputObject) {
|
||||
if (!inputObject || !inputObject.spec) {
|
||||
return;
|
||||
}
|
||||
if (utility_1.isEqual(inputObject.kind, 'pod')
|
||||
&& inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.imagePullSecrets) {
|
||||
return inputObject.spec.imagePullSecrets;
|
||||
}
|
||||
else if (utility_1.isEqual(inputObject.kind, 'cronjob')
|
||||
&& inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.jobTemplate
|
||||
&& inputObject.spec.jobTemplate.spec
|
||||
&& inputObject.spec.jobTemplate.spec.template
|
||||
&& inputObject.spec.jobTemplate.spec.template.spec
|
||||
&& inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets) {
|
||||
return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
else if (inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.template
|
||||
&& inputObject.spec.template.spec
|
||||
&& inputObject.spec.template.spec.imagePullSecrets) {
|
||||
return inputObject.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
}
|
||||
function setImagePullSecrets(inputObject, newImagePullSecrets) {
|
||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||
return;
|
||||
}
|
||||
if (utility_1.isEqual(inputObject.kind, 'pod')) {
|
||||
if (inputObject
|
||||
&& inputObject.spec) {
|
||||
if (newImagePullSecrets.length > 0) {
|
||||
inputObject.spec.imagePullSecrets = newImagePullSecrets;
|
||||
}
|
||||
else {
|
||||
delete inputObject.spec.imagePullSecrets;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (utility_1.isEqual(inputObject.kind, 'cronjob')) {
|
||||
if (inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.jobTemplate
|
||||
&& inputObject.spec.jobTemplate.spec
|
||||
&& inputObject.spec.jobTemplate.spec.template
|
||||
&& inputObject.spec.jobTemplate.spec.template.spec) {
|
||||
if (newImagePullSecrets.length > 0) {
|
||||
inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
|
||||
}
|
||||
else {
|
||||
delete inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
|
||||
if (inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.template
|
||||
&& inputObject.spec.template.spec) {
|
||||
if (newImagePullSecrets.length > 0) {
|
||||
inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
|
||||
}
|
||||
else {
|
||||
delete inputObject.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function substituteImageNameInSpecContent(currentString, imageName, imageNameWithNewTag) {
|
||||
if (currentString.indexOf(imageName) < 0) {
|
||||
core.debug(`No occurence of replacement token: ${imageName} found`);
|
||||
return currentString;
|
||||
}
|
||||
return currentString.split('\n').reduce((acc, line) => {
|
||||
const imageKeyword = line.match(/^ *image:/);
|
||||
if (imageKeyword) {
|
||||
const [currentImageName, currentImageTag] = line
|
||||
.substring(imageKeyword[0].length) // consume the line from keyword onwards
|
||||
.trim()
|
||||
.replace(/[',"]/g, '') // replace allowed quotes with nothing
|
||||
.split(':');
|
||||
if (currentImageName === imageName) {
|
||||
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
|
||||
}
|
||||
}
|
||||
return acc + line + '\n';
|
||||
}, '');
|
||||
}
|
||||
function updateContainerImagesInManifestFiles(filePaths, containers) {
|
||||
if (!!containers && containers.length > 0) {
|
||||
const newFilePaths = [];
|
||||
const tempDirectory = fileHelper.getTempDirectory();
|
||||
filePaths.forEach((filePath) => {
|
||||
let contents = fs.readFileSync(filePath).toString();
|
||||
containers.forEach((container) => {
|
||||
let imageName = container.split(':')[0];
|
||||
if (imageName.indexOf('@') > 0) {
|
||||
imageName = imageName.split('@')[0];
|
||||
}
|
||||
if (contents.indexOf(imageName) > 0) {
|
||||
contents = substituteImageNameInSpecFile(contents, imageName, container);
|
||||
}
|
||||
});
|
||||
const fileName = path.join(tempDirectory, path.basename(filePath));
|
||||
fs.writeFileSync(path.join(fileName), contents);
|
||||
newFilePaths.push(fileName);
|
||||
});
|
||||
return newFilePaths;
|
||||
}
|
||||
return filePaths;
|
||||
}
|
||||
function updateImagePullSecrets(inputObject, newImagePullSecrets) {
|
||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||
return;
|
||||
}
|
||||
let newImagePullSecretsObjects;
|
||||
if (newImagePullSecrets.length > 0) {
|
||||
newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return !!x ? { 'name': x } : null; });
|
||||
}
|
||||
else {
|
||||
newImagePullSecretsObjects = [];
|
||||
}
|
||||
let existingImagePullSecretObjects = getImagePullSecrets(inputObject);
|
||||
if (!existingImagePullSecretObjects) {
|
||||
existingImagePullSecretObjects = new Array();
|
||||
}
|
||||
existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects);
|
||||
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
|
||||
}
|
||||
exports.updateImagePullSecrets = updateImagePullSecrets;
|
||||
function updateImagePullSecretsInManifestFiles(filePaths, imagePullSecrets) {
|
||||
if (!!imagePullSecrets && imagePullSecrets.length > 0) {
|
||||
const newObjectsList = [];
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath).toString();
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
if (!!inputObject && !!inputObject.kind) {
|
||||
const kind = inputObject.kind;
|
||||
if (KubernetesObjectUtility.isWorkloadEntity(kind)) {
|
||||
KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false);
|
||||
}
|
||||
newObjectsList.push(inputObject);
|
||||
}
|
||||
});
|
||||
});
|
||||
core.debug('New K8s objects after adding imagePullSecrets are :' + JSON.stringify(newObjectsList));
|
||||
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
return newFilePaths;
|
||||
}
|
||||
return filePaths;
|
||||
}
|
||||
function getUpdatedManifestFiles(manifestFilePaths) {
|
||||
let inputManifestFiles = getManifestFiles(manifestFilePaths);
|
||||
if (!inputManifestFiles || inputManifestFiles.length === 0) {
|
||||
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
|
||||
}
|
||||
// artifact substitution
|
||||
inputManifestFiles = updateContainerImagesInManifestFiles(inputManifestFiles, TaskInputParameters.containers);
|
||||
// imagePullSecrets addition
|
||||
inputManifestFiles = updateImagePullSecretsInManifestFiles(inputManifestFiles, TaskInputParameters.imagePullSecrets);
|
||||
return inputManifestFiles;
|
||||
}
|
||||
exports.getUpdatedManifestFiles = getUpdatedManifestFiles;
|
||||
const workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
|
||||
function isWorkloadEntity(kind) {
|
||||
if (!kind) {
|
||||
core.debug('ResourceKindNotDefined');
|
||||
return false;
|
||||
}
|
||||
return workloadTypes.some((type) => {
|
||||
return utility_1.isEqual(type, kind);
|
||||
});
|
||||
}
|
||||
exports.isWorkloadEntity = isWorkloadEntity;
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isWorkloadEntity = exports.getUpdatedManifestFiles = exports.updateImagePullSecrets = exports.substituteImageNameInSpecFile = exports.getDeleteCmdArgs = exports.createKubectlArgs = exports.getKubectl = exports.getManifestFiles = void 0;
|
||||
const core = require("@actions/core");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const path = require("path");
|
||||
const kubectlutility = require("./kubectl-util");
|
||||
const io = require("@actions/io");
|
||||
const utility_1 = require("./utility");
|
||||
const fileHelper = require("./files-helper");
|
||||
const KubernetesObjectUtility = require("./resource-object-utility");
|
||||
const TaskInputParameters = require("../input-parameters");
|
||||
function getManifestFiles(manifestFilePaths) {
|
||||
if (!manifestFilePaths) {
|
||||
core.debug('file input is not present');
|
||||
return null;
|
||||
}
|
||||
return manifestFilePaths;
|
||||
}
|
||||
exports.getManifestFiles = getManifestFiles;
|
||||
function getKubectl() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
return Promise.resolve(io.which('kubectl', true));
|
||||
}
|
||||
catch (ex) {
|
||||
return kubectlutility.downloadKubectl(yield kubectlutility.getStableKubectlVersion());
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.getKubectl = getKubectl;
|
||||
function createKubectlArgs(kinds, names) {
|
||||
let args = '';
|
||||
if (!!kinds && kinds.size > 0) {
|
||||
args = args + createInlineArray(Array.from(kinds.values()));
|
||||
}
|
||||
if (!!names && names.size > 0) {
|
||||
args = args + ' ' + Array.from(names.values()).join(' ');
|
||||
}
|
||||
return args;
|
||||
}
|
||||
exports.createKubectlArgs = createKubectlArgs;
|
||||
function getDeleteCmdArgs(argsPrefix, inputArgs) {
|
||||
let args = '';
|
||||
if (!!argsPrefix && argsPrefix.length > 0) {
|
||||
args = argsPrefix;
|
||||
}
|
||||
if (!!inputArgs && inputArgs.length > 0) {
|
||||
if (args.length > 0) {
|
||||
args = args + ' ';
|
||||
}
|
||||
args = args + inputArgs;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
exports.getDeleteCmdArgs = getDeleteCmdArgs;
|
||||
/*
|
||||
For example,
|
||||
currentString: `image: "example/example-image"`
|
||||
imageName: `example/example-image`
|
||||
imageNameWithNewTag: `example/example-image:identifiertag`
|
||||
|
||||
This substituteImageNameInSpecFile function would return
|
||||
return Value: `image: "example/example-image:identifiertag"`
|
||||
*/
|
||||
function substituteImageNameInSpecFile(currentString, imageName, imageNameWithNewTag) {
|
||||
if (currentString.indexOf(imageName) < 0) {
|
||||
core.debug(`No occurence of replacement token: ${imageName} found`);
|
||||
return currentString;
|
||||
}
|
||||
return currentString.split('\n').reduce((acc, line) => {
|
||||
const imageKeyword = line.match(/^ *image:/);
|
||||
if (imageKeyword) {
|
||||
let [currentImageName, currentImageTag] = line
|
||||
.substring(imageKeyword[0].length) // consume the line from keyword onwards
|
||||
.trim()
|
||||
.replace(/[',"]/g, '') // replace allowed quotes with nothing
|
||||
.split(':');
|
||||
if (!currentImageTag && currentImageName.indexOf(' ') > 0) {
|
||||
currentImageName = currentImageName.split(' ')[0]; // Stripping off comments
|
||||
}
|
||||
if (currentImageName === imageName) {
|
||||
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
|
||||
}
|
||||
}
|
||||
return acc + line + '\n';
|
||||
}, '');
|
||||
}
|
||||
exports.substituteImageNameInSpecFile = substituteImageNameInSpecFile;
|
||||
function createInlineArray(str) {
|
||||
if (typeof str === 'string') {
|
||||
return str;
|
||||
}
|
||||
return str.join(',');
|
||||
}
|
||||
function getImagePullSecrets(inputObject) {
|
||||
if (!inputObject || !inputObject.spec) {
|
||||
return;
|
||||
}
|
||||
if (utility_1.isEqual(inputObject.kind, 'pod')
|
||||
&& inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.imagePullSecrets) {
|
||||
return inputObject.spec.imagePullSecrets;
|
||||
}
|
||||
else if (utility_1.isEqual(inputObject.kind, 'cronjob')
|
||||
&& inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.jobTemplate
|
||||
&& inputObject.spec.jobTemplate.spec
|
||||
&& inputObject.spec.jobTemplate.spec.template
|
||||
&& inputObject.spec.jobTemplate.spec.template.spec
|
||||
&& inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets) {
|
||||
return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
else if (inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.template
|
||||
&& inputObject.spec.template.spec
|
||||
&& inputObject.spec.template.spec.imagePullSecrets) {
|
||||
return inputObject.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
}
|
||||
function setImagePullSecrets(inputObject, newImagePullSecrets) {
|
||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||
return;
|
||||
}
|
||||
if (utility_1.isEqual(inputObject.kind, 'pod')) {
|
||||
if (inputObject
|
||||
&& inputObject.spec) {
|
||||
if (newImagePullSecrets.length > 0) {
|
||||
inputObject.spec.imagePullSecrets = newImagePullSecrets;
|
||||
}
|
||||
else {
|
||||
delete inputObject.spec.imagePullSecrets;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (utility_1.isEqual(inputObject.kind, 'cronjob')) {
|
||||
if (inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.jobTemplate
|
||||
&& inputObject.spec.jobTemplate.spec
|
||||
&& inputObject.spec.jobTemplate.spec.template
|
||||
&& inputObject.spec.jobTemplate.spec.template.spec) {
|
||||
if (newImagePullSecrets.length > 0) {
|
||||
inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
|
||||
}
|
||||
else {
|
||||
delete inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
|
||||
if (inputObject
|
||||
&& inputObject.spec
|
||||
&& inputObject.spec.template
|
||||
&& inputObject.spec.template.spec) {
|
||||
if (newImagePullSecrets.length > 0) {
|
||||
inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
|
||||
}
|
||||
else {
|
||||
delete inputObject.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function substituteImageNameInSpecContent(currentString, imageName, imageNameWithNewTag) {
|
||||
if (currentString.indexOf(imageName) < 0) {
|
||||
core.debug(`No occurence of replacement token: ${imageName} found`);
|
||||
return currentString;
|
||||
}
|
||||
return currentString.split('\n').reduce((acc, line) => {
|
||||
const imageKeyword = line.match(/^ *image:/);
|
||||
if (imageKeyword) {
|
||||
const [currentImageName, currentImageTag] = line
|
||||
.substring(imageKeyword[0].length) // consume the line from keyword onwards
|
||||
.trim()
|
||||
.replace(/[',"]/g, '') // replace allowed quotes with nothing
|
||||
.split(':');
|
||||
if (currentImageName === imageName) {
|
||||
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
|
||||
}
|
||||
}
|
||||
return acc + line + '\n';
|
||||
}, '');
|
||||
}
|
||||
function updateContainerImagesInManifestFiles(filePaths, containers) {
|
||||
if (!!containers && containers.length > 0) {
|
||||
const newFilePaths = [];
|
||||
const tempDirectory = fileHelper.getTempDirectory();
|
||||
filePaths.forEach((filePath) => {
|
||||
let contents = fs.readFileSync(filePath).toString();
|
||||
containers.forEach((container) => {
|
||||
let imageName = container.split(':')[0];
|
||||
if (imageName.indexOf('@') > 0) {
|
||||
imageName = imageName.split('@')[0];
|
||||
}
|
||||
if (contents.indexOf(imageName) > 0) {
|
||||
contents = substituteImageNameInSpecFile(contents, imageName, container);
|
||||
}
|
||||
});
|
||||
const fileName = path.join(tempDirectory, path.basename(filePath));
|
||||
fs.writeFileSync(path.join(fileName), contents);
|
||||
newFilePaths.push(fileName);
|
||||
});
|
||||
return newFilePaths;
|
||||
}
|
||||
return filePaths;
|
||||
}
|
||||
function updateImagePullSecrets(inputObject, newImagePullSecrets) {
|
||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||
return;
|
||||
}
|
||||
let newImagePullSecretsObjects;
|
||||
if (newImagePullSecrets.length > 0) {
|
||||
newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return !!x ? { 'name': x } : null; });
|
||||
}
|
||||
else {
|
||||
newImagePullSecretsObjects = [];
|
||||
}
|
||||
let existingImagePullSecretObjects = getImagePullSecrets(inputObject);
|
||||
if (!existingImagePullSecretObjects) {
|
||||
existingImagePullSecretObjects = new Array();
|
||||
}
|
||||
existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects);
|
||||
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
|
||||
}
|
||||
exports.updateImagePullSecrets = updateImagePullSecrets;
|
||||
function updateImagePullSecretsInManifestFiles(filePaths, imagePullSecrets) {
|
||||
if (!!imagePullSecrets && imagePullSecrets.length > 0) {
|
||||
const newObjectsList = [];
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath).toString();
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
if (!!inputObject && !!inputObject.kind) {
|
||||
const kind = inputObject.kind;
|
||||
if (KubernetesObjectUtility.isWorkloadEntity(kind)) {
|
||||
KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false);
|
||||
}
|
||||
newObjectsList.push(inputObject);
|
||||
}
|
||||
});
|
||||
});
|
||||
core.debug('New K8s objects after adding imagePullSecrets are :' + JSON.stringify(newObjectsList));
|
||||
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
return newFilePaths;
|
||||
}
|
||||
return filePaths;
|
||||
}
|
||||
function getUpdatedManifestFiles(manifestFilePaths) {
|
||||
let inputManifestFiles = getManifestFiles(manifestFilePaths);
|
||||
if (!inputManifestFiles || inputManifestFiles.length === 0) {
|
||||
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
|
||||
}
|
||||
// artifact substitution
|
||||
inputManifestFiles = updateContainerImagesInManifestFiles(inputManifestFiles, TaskInputParameters.containers);
|
||||
// imagePullSecrets addition
|
||||
inputManifestFiles = updateImagePullSecretsInManifestFiles(inputManifestFiles, TaskInputParameters.imagePullSecrets);
|
||||
return inputManifestFiles;
|
||||
}
|
||||
exports.getUpdatedManifestFiles = getUpdatedManifestFiles;
|
||||
const workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
|
||||
function isWorkloadEntity(kind) {
|
||||
if (!kind) {
|
||||
core.debug('ResourceKindNotDefined');
|
||||
return false;
|
||||
}
|
||||
return workloadTypes.some((type) => {
|
||||
return utility_1.isEqual(type, kind);
|
||||
});
|
||||
}
|
||||
exports.isWorkloadEntity = isWorkloadEntity;
|
||||
|
||||
@@ -1,277 +1,277 @@
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getResources = exports.updateSelectorLabels = exports.updateSpecLabels = exports.updateImagePullSecrets = exports.updateObjectAnnotations = exports.updateObjectLabels = exports.getReplicaCount = exports.isIngressEntity = exports.isServiceEntity = exports.isWorkloadEntity = exports.isDeploymentEntity = void 0;
|
||||
const fs = require("fs");
|
||||
const core = require("@actions/core");
|
||||
const yaml = require("js-yaml");
|
||||
const constants_1 = require("../constants");
|
||||
const string_comparison_1 = require("./string-comparison");
|
||||
const INGRESS = "Ingress";
|
||||
function isDeploymentEntity(kind) {
|
||||
if (!kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
return constants_1.deploymentTypes.some((type) => {
|
||||
return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||
});
|
||||
}
|
||||
exports.isDeploymentEntity = isDeploymentEntity;
|
||||
function isWorkloadEntity(kind) {
|
||||
if (!kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
return constants_1.workloadTypes.some((type) => {
|
||||
return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||
});
|
||||
}
|
||||
exports.isWorkloadEntity = isWorkloadEntity;
|
||||
function isServiceEntity(kind) {
|
||||
if (!kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
return string_comparison_1.isEqual("Service", kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
exports.isServiceEntity = isServiceEntity;
|
||||
function isIngressEntity(kind) {
|
||||
if (!kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
return string_comparison_1.isEqual(INGRESS, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
exports.isIngressEntity = isIngressEntity;
|
||||
function getReplicaCount(inputObject) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
const kind = inputObject.kind;
|
||||
if (!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) && !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
return inputObject.spec.replicas;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
exports.getReplicaCount = getReplicaCount;
|
||||
function updateObjectLabels(inputObject, newLabels, override) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.metadata) {
|
||||
throw ('NullInputObjectMetadata');
|
||||
}
|
||||
if (!newLabels) {
|
||||
return;
|
||||
}
|
||||
if (override) {
|
||||
inputObject.metadata.labels = newLabels;
|
||||
}
|
||||
else {
|
||||
let existingLabels = inputObject.metadata.labels;
|
||||
if (!existingLabels) {
|
||||
existingLabels = new Map();
|
||||
}
|
||||
Object.keys(newLabels).forEach(function (key) {
|
||||
existingLabels[key] = newLabels[key];
|
||||
});
|
||||
inputObject.metadata.labels = existingLabels;
|
||||
}
|
||||
}
|
||||
exports.updateObjectLabels = updateObjectLabels;
|
||||
function updateObjectAnnotations(inputObject, newAnnotations, override) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.metadata) {
|
||||
throw ('NullInputObjectMetadata');
|
||||
}
|
||||
if (!newAnnotations) {
|
||||
return;
|
||||
}
|
||||
if (override) {
|
||||
inputObject.metadata.annotations = newAnnotations;
|
||||
}
|
||||
else {
|
||||
let existingAnnotations = inputObject.metadata.annotations;
|
||||
if (!existingAnnotations) {
|
||||
existingAnnotations = new Map();
|
||||
}
|
||||
Object.keys(newAnnotations).forEach(function (key) {
|
||||
existingAnnotations[key] = newAnnotations[key];
|
||||
});
|
||||
inputObject.metadata.annotations = existingAnnotations;
|
||||
}
|
||||
}
|
||||
exports.updateObjectAnnotations = updateObjectAnnotations;
|
||||
function updateImagePullSecrets(inputObject, newImagePullSecrets, override) {
|
||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||
return;
|
||||
}
|
||||
const newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return { 'name': x }; });
|
||||
let existingImagePullSecretObjects = getImagePullSecrets(inputObject);
|
||||
if (override) {
|
||||
existingImagePullSecretObjects = newImagePullSecretsObjects;
|
||||
}
|
||||
else {
|
||||
if (!existingImagePullSecretObjects) {
|
||||
existingImagePullSecretObjects = new Array();
|
||||
}
|
||||
existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects);
|
||||
}
|
||||
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
|
||||
}
|
||||
exports.updateImagePullSecrets = updateImagePullSecrets;
|
||||
function updateSpecLabels(inputObject, newLabels, override) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
if (!newLabels) {
|
||||
return;
|
||||
}
|
||||
let existingLabels = getSpecLabels(inputObject);
|
||||
if (override) {
|
||||
existingLabels = newLabels;
|
||||
}
|
||||
else {
|
||||
if (!existingLabels) {
|
||||
existingLabels = new Map();
|
||||
}
|
||||
Object.keys(newLabels).forEach(function (key) {
|
||||
existingLabels[key] = newLabels[key];
|
||||
});
|
||||
}
|
||||
setSpecLabels(inputObject, existingLabels);
|
||||
}
|
||||
exports.updateSpecLabels = updateSpecLabels;
|
||||
function updateSelectorLabels(inputObject, newLabels, override) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
if (!newLabels) {
|
||||
return;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
return;
|
||||
}
|
||||
let existingLabels = getSpecSelectorLabels(inputObject);
|
||||
if (override) {
|
||||
existingLabels = newLabels;
|
||||
}
|
||||
else {
|
||||
if (!existingLabels) {
|
||||
existingLabels = new Map();
|
||||
}
|
||||
Object.keys(newLabels).forEach(function (key) {
|
||||
existingLabels[key] = newLabels[key];
|
||||
});
|
||||
}
|
||||
setSpecSelectorLabels(inputObject, existingLabels);
|
||||
}
|
||||
exports.updateSelectorLabels = updateSelectorLabels;
|
||||
function getResources(filePaths, filterResourceTypes) {
|
||||
if (!filePaths) {
|
||||
return [];
|
||||
}
|
||||
const resources = [];
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const inputObjectKind = inputObject ? inputObject.kind : '';
|
||||
if (filterResourceTypes.filter(type => string_comparison_1.isEqual(inputObjectKind, type, string_comparison_1.StringComparer.OrdinalIgnoreCase)).length > 0) {
|
||||
const resource = {
|
||||
type: inputObject.kind,
|
||||
name: inputObject.metadata.name
|
||||
};
|
||||
resources.push(resource);
|
||||
}
|
||||
});
|
||||
});
|
||||
return resources;
|
||||
}
|
||||
exports.getResources = getResources;
|
||||
function getSpecLabels(inputObject) {
|
||||
if (!inputObject) {
|
||||
return null;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
return inputObject.metadata.labels;
|
||||
}
|
||||
if (!!inputObject.spec && !!inputObject.spec.template && !!inputObject.spec.template.metadata) {
|
||||
return inputObject.spec.template.metadata.labels;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function getImagePullSecrets(inputObject) {
|
||||
if (!inputObject || !inputObject.spec) {
|
||||
return null;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
try {
|
||||
return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug(`Fetching imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
return inputObject.spec.imagePullSecrets;
|
||||
}
|
||||
if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
|
||||
return inputObject.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function setImagePullSecrets(inputObject, newImagePullSecrets) {
|
||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||
return;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
inputObject.spec.imagePullSecrets = newImagePullSecrets;
|
||||
return;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
try {
|
||||
inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug(`Overriding imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
|
||||
//Do nothing
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
|
||||
inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
function setSpecLabels(inputObject, newLabels) {
|
||||
let specLabels = getSpecLabels(inputObject);
|
||||
if (!!newLabels) {
|
||||
specLabels = newLabels;
|
||||
}
|
||||
}
|
||||
function getSpecSelectorLabels(inputObject) {
|
||||
if (!!inputObject && !!inputObject.spec && !!inputObject.spec.selector) {
|
||||
if (isServiceEntity(inputObject.kind)) {
|
||||
return inputObject.spec.selector;
|
||||
}
|
||||
else {
|
||||
return inputObject.spec.selector.matchLabels;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function setSpecSelectorLabels(inputObject, newLabels) {
|
||||
let selectorLabels = getSpecSelectorLabels(inputObject);
|
||||
if (!!selectorLabels) {
|
||||
selectorLabels = newLabels;
|
||||
}
|
||||
}
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getResources = exports.updateSelectorLabels = exports.updateSpecLabels = exports.updateImagePullSecrets = exports.updateObjectAnnotations = exports.updateObjectLabels = exports.getReplicaCount = exports.isIngressEntity = exports.isServiceEntity = exports.isWorkloadEntity = exports.isDeploymentEntity = void 0;
|
||||
const fs = require("fs");
|
||||
const core = require("@actions/core");
|
||||
const yaml = require("js-yaml");
|
||||
const constants_1 = require("../constants");
|
||||
const string_comparison_1 = require("./string-comparison");
|
||||
const INGRESS = "Ingress";
|
||||
function isDeploymentEntity(kind) {
|
||||
if (!kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
return constants_1.deploymentTypes.some((type) => {
|
||||
return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||
});
|
||||
}
|
||||
exports.isDeploymentEntity = isDeploymentEntity;
|
||||
function isWorkloadEntity(kind) {
|
||||
if (!kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
return constants_1.workloadTypes.some((type) => {
|
||||
return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||
});
|
||||
}
|
||||
exports.isWorkloadEntity = isWorkloadEntity;
|
||||
function isServiceEntity(kind) {
|
||||
if (!kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
return string_comparison_1.isEqual("Service", kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
exports.isServiceEntity = isServiceEntity;
|
||||
function isIngressEntity(kind) {
|
||||
if (!kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
return string_comparison_1.isEqual(INGRESS, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
exports.isIngressEntity = isIngressEntity;
|
||||
function getReplicaCount(inputObject) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
const kind = inputObject.kind;
|
||||
if (!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) && !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
return inputObject.spec.replicas;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
exports.getReplicaCount = getReplicaCount;
|
||||
function updateObjectLabels(inputObject, newLabels, override) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.metadata) {
|
||||
throw ('NullInputObjectMetadata');
|
||||
}
|
||||
if (!newLabels) {
|
||||
return;
|
||||
}
|
||||
if (override) {
|
||||
inputObject.metadata.labels = newLabels;
|
||||
}
|
||||
else {
|
||||
let existingLabels = inputObject.metadata.labels;
|
||||
if (!existingLabels) {
|
||||
existingLabels = new Map();
|
||||
}
|
||||
Object.keys(newLabels).forEach(function (key) {
|
||||
existingLabels[key] = newLabels[key];
|
||||
});
|
||||
inputObject.metadata.labels = existingLabels;
|
||||
}
|
||||
}
|
||||
exports.updateObjectLabels = updateObjectLabels;
|
||||
function updateObjectAnnotations(inputObject, newAnnotations, override) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.metadata) {
|
||||
throw ('NullInputObjectMetadata');
|
||||
}
|
||||
if (!newAnnotations) {
|
||||
return;
|
||||
}
|
||||
if (override) {
|
||||
inputObject.metadata.annotations = newAnnotations;
|
||||
}
|
||||
else {
|
||||
let existingAnnotations = inputObject.metadata.annotations;
|
||||
if (!existingAnnotations) {
|
||||
existingAnnotations = new Map();
|
||||
}
|
||||
Object.keys(newAnnotations).forEach(function (key) {
|
||||
existingAnnotations[key] = newAnnotations[key];
|
||||
});
|
||||
inputObject.metadata.annotations = existingAnnotations;
|
||||
}
|
||||
}
|
||||
exports.updateObjectAnnotations = updateObjectAnnotations;
|
||||
function updateImagePullSecrets(inputObject, newImagePullSecrets, override) {
|
||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||
return;
|
||||
}
|
||||
const newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return { 'name': x }; });
|
||||
let existingImagePullSecretObjects = getImagePullSecrets(inputObject);
|
||||
if (override) {
|
||||
existingImagePullSecretObjects = newImagePullSecretsObjects;
|
||||
}
|
||||
else {
|
||||
if (!existingImagePullSecretObjects) {
|
||||
existingImagePullSecretObjects = new Array();
|
||||
}
|
||||
existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects);
|
||||
}
|
||||
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
|
||||
}
|
||||
exports.updateImagePullSecrets = updateImagePullSecrets;
|
||||
function updateSpecLabels(inputObject, newLabels, override) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
if (!newLabels) {
|
||||
return;
|
||||
}
|
||||
let existingLabels = getSpecLabels(inputObject);
|
||||
if (override) {
|
||||
existingLabels = newLabels;
|
||||
}
|
||||
else {
|
||||
if (!existingLabels) {
|
||||
existingLabels = new Map();
|
||||
}
|
||||
Object.keys(newLabels).forEach(function (key) {
|
||||
existingLabels[key] = newLabels[key];
|
||||
});
|
||||
}
|
||||
setSpecLabels(inputObject, existingLabels);
|
||||
}
|
||||
exports.updateSpecLabels = updateSpecLabels;
|
||||
function updateSelectorLabels(inputObject, newLabels, override) {
|
||||
if (!inputObject) {
|
||||
throw ('NullInputObject');
|
||||
}
|
||||
if (!inputObject.kind) {
|
||||
throw ('ResourceKindNotDefined');
|
||||
}
|
||||
if (!newLabels) {
|
||||
return;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
return;
|
||||
}
|
||||
let existingLabels = getSpecSelectorLabels(inputObject);
|
||||
if (override) {
|
||||
existingLabels = newLabels;
|
||||
}
|
||||
else {
|
||||
if (!existingLabels) {
|
||||
existingLabels = new Map();
|
||||
}
|
||||
Object.keys(newLabels).forEach(function (key) {
|
||||
existingLabels[key] = newLabels[key];
|
||||
});
|
||||
}
|
||||
setSpecSelectorLabels(inputObject, existingLabels);
|
||||
}
|
||||
exports.updateSelectorLabels = updateSelectorLabels;
|
||||
function getResources(filePaths, filterResourceTypes) {
|
||||
if (!filePaths) {
|
||||
return [];
|
||||
}
|
||||
const resources = [];
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const inputObjectKind = inputObject ? inputObject.kind : '';
|
||||
if (filterResourceTypes.filter(type => string_comparison_1.isEqual(inputObjectKind, type, string_comparison_1.StringComparer.OrdinalIgnoreCase)).length > 0) {
|
||||
const resource = {
|
||||
type: inputObject.kind,
|
||||
name: inputObject.metadata.name
|
||||
};
|
||||
resources.push(resource);
|
||||
}
|
||||
});
|
||||
});
|
||||
return resources;
|
||||
}
|
||||
exports.getResources = getResources;
|
||||
function getSpecLabels(inputObject) {
|
||||
if (!inputObject) {
|
||||
return null;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
return inputObject.metadata.labels;
|
||||
}
|
||||
if (!!inputObject.spec && !!inputObject.spec.template && !!inputObject.spec.template.metadata) {
|
||||
return inputObject.spec.template.metadata.labels;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function getImagePullSecrets(inputObject) {
|
||||
if (!inputObject || !inputObject.spec) {
|
||||
return null;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
try {
|
||||
return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug(`Fetching imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
return inputObject.spec.imagePullSecrets;
|
||||
}
|
||||
if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
|
||||
return inputObject.spec.template.spec.imagePullSecrets;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function setImagePullSecrets(inputObject, newImagePullSecrets) {
|
||||
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
|
||||
return;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
inputObject.spec.imagePullSecrets = newImagePullSecrets;
|
||||
return;
|
||||
}
|
||||
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
|
||||
try {
|
||||
inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug(`Overriding imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
|
||||
//Do nothing
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
|
||||
inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
function setSpecLabels(inputObject, newLabels) {
|
||||
let specLabels = getSpecLabels(inputObject);
|
||||
if (!!newLabels) {
|
||||
specLabels = newLabels;
|
||||
}
|
||||
}
|
||||
function getSpecSelectorLabels(inputObject) {
|
||||
if (!!inputObject && !!inputObject.spec && !!inputObject.spec.selector) {
|
||||
if (isServiceEntity(inputObject.kind)) {
|
||||
return inputObject.spec.selector;
|
||||
}
|
||||
else {
|
||||
return inputObject.spec.selector.matchLabels;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function setSpecSelectorLabels(inputObject, newLabels) {
|
||||
let selectorLabels = getSpecSelectorLabels(inputObject);
|
||||
if (!!selectorLabels) {
|
||||
selectorLabels = newLabels;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,187 +1,187 @@
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getStableResourceName = exports.getBaselineResourceName = exports.getCanaryResourceName = exports.isSMICanaryStrategy = exports.isCanaryDeploymentStrategy = exports.fetchResource = exports.fetchCanaryResource = exports.getNewCanaryResource = exports.getNewBaselineResource = exports.getStableResource = exports.isResourceMarkedAsStable = exports.markResourceAsStable = exports.deleteCanaryDeployment = exports.STABLE_LABEL_VALUE = exports.STABLE_SUFFIX = exports.CANARY_LABEL_VALUE = exports.BASELINE_LABEL_VALUE = exports.CANARY_VERSION_LABEL = exports.TRAFFIC_SPLIT_STRATEGY = exports.CANARY_DEPLOYMENT_STRATEGY = void 0;
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const core = require("@actions/core");
|
||||
const TaskInputParameters = require("../../input-parameters");
|
||||
const helper = require("../resource-object-utility");
|
||||
const constants_1 = require("../../constants");
|
||||
const string_comparison_1 = require("../string-comparison");
|
||||
const utility_1 = require("../utility");
|
||||
const utils = require("../manifest-utilities");
|
||||
exports.CANARY_DEPLOYMENT_STRATEGY = 'CANARY';
|
||||
exports.TRAFFIC_SPLIT_STRATEGY = 'SMI';
|
||||
exports.CANARY_VERSION_LABEL = 'workflow/version';
|
||||
const BASELINE_SUFFIX = '-baseline';
|
||||
exports.BASELINE_LABEL_VALUE = 'baseline';
|
||||
const CANARY_SUFFIX = '-canary';
|
||||
exports.CANARY_LABEL_VALUE = 'canary';
|
||||
exports.STABLE_SUFFIX = '-stable';
|
||||
exports.STABLE_LABEL_VALUE = 'stable';
|
||||
function deleteCanaryDeployment(kubectl, manifestFilePaths, includeServices) {
|
||||
// get manifest files
|
||||
const inputManifestFiles = utils.getManifestFiles(manifestFilePaths);
|
||||
if (inputManifestFiles == null || inputManifestFiles.length == 0) {
|
||||
throw new Error('ManifestFileNotFound');
|
||||
}
|
||||
// create delete cmd prefix
|
||||
cleanUpCanary(kubectl, inputManifestFiles, includeServices);
|
||||
}
|
||||
exports.deleteCanaryDeployment = deleteCanaryDeployment;
|
||||
function markResourceAsStable(inputObject) {
|
||||
if (isResourceMarkedAsStable(inputObject)) {
|
||||
return inputObject;
|
||||
}
|
||||
const newObject = JSON.parse(JSON.stringify(inputObject));
|
||||
// Adding labels and annotations.
|
||||
addCanaryLabelsAndAnnotations(newObject, exports.STABLE_LABEL_VALUE);
|
||||
core.debug("Added stable label: " + JSON.stringify(newObject));
|
||||
return newObject;
|
||||
}
|
||||
exports.markResourceAsStable = markResourceAsStable;
|
||||
function isResourceMarkedAsStable(inputObject) {
|
||||
return inputObject &&
|
||||
inputObject.metadata &&
|
||||
inputObject.metadata.labels &&
|
||||
inputObject.metadata.labels[exports.CANARY_VERSION_LABEL] == exports.STABLE_LABEL_VALUE;
|
||||
}
|
||||
exports.isResourceMarkedAsStable = isResourceMarkedAsStable;
|
||||
function getStableResource(inputObject) {
|
||||
var replicaCount = isSpecContainsReplicas(inputObject.kind) ? inputObject.metadata.replicas : 0;
|
||||
return getNewCanaryObject(inputObject, replicaCount, exports.STABLE_LABEL_VALUE);
|
||||
}
|
||||
exports.getStableResource = getStableResource;
|
||||
function getNewBaselineResource(stableObject, replicas) {
|
||||
return getNewCanaryObject(stableObject, replicas, exports.BASELINE_LABEL_VALUE);
|
||||
}
|
||||
exports.getNewBaselineResource = getNewBaselineResource;
|
||||
function getNewCanaryResource(inputObject, replicas) {
|
||||
return getNewCanaryObject(inputObject, replicas, exports.CANARY_LABEL_VALUE);
|
||||
}
|
||||
exports.getNewCanaryResource = getNewCanaryResource;
|
||||
function fetchCanaryResource(kubectl, kind, name) {
|
||||
return fetchResource(kubectl, kind, getCanaryResourceName(name));
|
||||
}
|
||||
exports.fetchCanaryResource = fetchCanaryResource;
|
||||
function fetchResource(kubectl, kind, name) {
|
||||
const result = kubectl.getResource(kind, name);
|
||||
if (result == null || !!result.stderr) {
|
||||
return null;
|
||||
}
|
||||
if (!!result.stdout) {
|
||||
const resource = JSON.parse(result.stdout);
|
||||
try {
|
||||
UnsetsClusterSpecficDetails(resource);
|
||||
return resource;
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug('Exception occurred while Parsing ' + resource + ' in Json object');
|
||||
core.debug(`Exception:${ex}`);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
exports.fetchResource = fetchResource;
|
||||
function isCanaryDeploymentStrategy() {
|
||||
const deploymentStrategy = TaskInputParameters.deploymentStrategy;
|
||||
return deploymentStrategy && deploymentStrategy.toUpperCase() === exports.CANARY_DEPLOYMENT_STRATEGY;
|
||||
}
|
||||
exports.isCanaryDeploymentStrategy = isCanaryDeploymentStrategy;
|
||||
function isSMICanaryStrategy() {
|
||||
const deploymentStrategy = TaskInputParameters.trafficSplitMethod;
|
||||
return isCanaryDeploymentStrategy() && deploymentStrategy && deploymentStrategy.toUpperCase() === exports.TRAFFIC_SPLIT_STRATEGY;
|
||||
}
|
||||
exports.isSMICanaryStrategy = isSMICanaryStrategy;
|
||||
function getCanaryResourceName(name) {
|
||||
return name + CANARY_SUFFIX;
|
||||
}
|
||||
exports.getCanaryResourceName = getCanaryResourceName;
|
||||
function getBaselineResourceName(name) {
|
||||
return name + BASELINE_SUFFIX;
|
||||
}
|
||||
exports.getBaselineResourceName = getBaselineResourceName;
|
||||
function getStableResourceName(name) {
|
||||
return name + exports.STABLE_SUFFIX;
|
||||
}
|
||||
exports.getStableResourceName = getStableResourceName;
|
||||
function UnsetsClusterSpecficDetails(resource) {
|
||||
if (resource == null) {
|
||||
return;
|
||||
}
|
||||
// Unsets the cluster specific details in the object
|
||||
if (!!resource) {
|
||||
const metadata = resource.metadata;
|
||||
const status = resource.status;
|
||||
if (!!metadata) {
|
||||
const newMetadata = {
|
||||
'annotations': metadata.annotations,
|
||||
'labels': metadata.labels,
|
||||
'name': metadata.name
|
||||
};
|
||||
resource.metadata = newMetadata;
|
||||
}
|
||||
if (!!status) {
|
||||
resource.status = {};
|
||||
}
|
||||
}
|
||||
}
|
||||
function getNewCanaryObject(inputObject, replicas, type) {
|
||||
const newObject = JSON.parse(JSON.stringify(inputObject));
|
||||
// Updating name
|
||||
if (type === exports.CANARY_LABEL_VALUE) {
|
||||
newObject.metadata.name = getCanaryResourceName(inputObject.metadata.name);
|
||||
}
|
||||
else if (type === exports.STABLE_LABEL_VALUE) {
|
||||
newObject.metadata.name = getStableResourceName(inputObject.metadata.name);
|
||||
}
|
||||
else {
|
||||
newObject.metadata.name = getBaselineResourceName(inputObject.metadata.name);
|
||||
}
|
||||
// Adding labels and annotations.
|
||||
addCanaryLabelsAndAnnotations(newObject, type);
|
||||
// Updating no. of replicas
|
||||
if (isSpecContainsReplicas(newObject.kind)) {
|
||||
newObject.spec.replicas = replicas;
|
||||
}
|
||||
return newObject;
|
||||
}
|
||||
function isSpecContainsReplicas(kind) {
|
||||
return !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) &&
|
||||
!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase) &&
|
||||
!helper.isServiceEntity(kind);
|
||||
}
|
||||
function addCanaryLabelsAndAnnotations(inputObject, type) {
|
||||
const newLabels = new Map();
|
||||
newLabels[exports.CANARY_VERSION_LABEL] = type;
|
||||
helper.updateObjectLabels(inputObject, newLabels, false);
|
||||
helper.updateObjectAnnotations(inputObject, newLabels, false);
|
||||
helper.updateSelectorLabels(inputObject, newLabels, false);
|
||||
if (!helper.isServiceEntity(inputObject.kind)) {
|
||||
helper.updateSpecLabels(inputObject, newLabels, false);
|
||||
}
|
||||
}
|
||||
function cleanUpCanary(kubectl, files, includeServices) {
|
||||
var deleteObject = function (kind, name) {
|
||||
try {
|
||||
const result = kubectl.delete([kind, name]);
|
||||
utility_1.checkForErrors([result]);
|
||||
}
|
||||
catch (ex) {
|
||||
// Ignore failures of delete if doesn't exist
|
||||
}
|
||||
};
|
||||
files.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isDeploymentEntity(kind) || (includeServices && helper.isServiceEntity(kind))) {
|
||||
const canaryObjectName = getCanaryResourceName(name);
|
||||
const baselineObjectName = getBaselineResourceName(name);
|
||||
deleteObject(kind, canaryObjectName);
|
||||
deleteObject(kind, baselineObjectName);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getStableResourceName = exports.getBaselineResourceName = exports.getCanaryResourceName = exports.isSMICanaryStrategy = exports.isCanaryDeploymentStrategy = exports.fetchResource = exports.fetchCanaryResource = exports.getNewCanaryResource = exports.getNewBaselineResource = exports.getStableResource = exports.isResourceMarkedAsStable = exports.markResourceAsStable = exports.deleteCanaryDeployment = exports.STABLE_LABEL_VALUE = exports.STABLE_SUFFIX = exports.CANARY_LABEL_VALUE = exports.BASELINE_LABEL_VALUE = exports.CANARY_VERSION_LABEL = exports.TRAFFIC_SPLIT_STRATEGY = exports.CANARY_DEPLOYMENT_STRATEGY = void 0;
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const core = require("@actions/core");
|
||||
const TaskInputParameters = require("../../input-parameters");
|
||||
const helper = require("../resource-object-utility");
|
||||
const constants_1 = require("../../constants");
|
||||
const string_comparison_1 = require("../string-comparison");
|
||||
const utility_1 = require("../utility");
|
||||
const utils = require("../manifest-utilities");
|
||||
exports.CANARY_DEPLOYMENT_STRATEGY = 'CANARY';
|
||||
exports.TRAFFIC_SPLIT_STRATEGY = 'SMI';
|
||||
exports.CANARY_VERSION_LABEL = 'workflow/version';
|
||||
const BASELINE_SUFFIX = '-baseline';
|
||||
exports.BASELINE_LABEL_VALUE = 'baseline';
|
||||
const CANARY_SUFFIX = '-canary';
|
||||
exports.CANARY_LABEL_VALUE = 'canary';
|
||||
exports.STABLE_SUFFIX = '-stable';
|
||||
exports.STABLE_LABEL_VALUE = 'stable';
|
||||
function deleteCanaryDeployment(kubectl, manifestFilePaths, includeServices) {
|
||||
// get manifest files
|
||||
const inputManifestFiles = utils.getManifestFiles(manifestFilePaths);
|
||||
if (inputManifestFiles == null || inputManifestFiles.length == 0) {
|
||||
throw new Error('ManifestFileNotFound');
|
||||
}
|
||||
// create delete cmd prefix
|
||||
cleanUpCanary(kubectl, inputManifestFiles, includeServices);
|
||||
}
|
||||
exports.deleteCanaryDeployment = deleteCanaryDeployment;
|
||||
function markResourceAsStable(inputObject) {
|
||||
if (isResourceMarkedAsStable(inputObject)) {
|
||||
return inputObject;
|
||||
}
|
||||
const newObject = JSON.parse(JSON.stringify(inputObject));
|
||||
// Adding labels and annotations.
|
||||
addCanaryLabelsAndAnnotations(newObject, exports.STABLE_LABEL_VALUE);
|
||||
core.debug("Added stable label: " + JSON.stringify(newObject));
|
||||
return newObject;
|
||||
}
|
||||
exports.markResourceAsStable = markResourceAsStable;
|
||||
function isResourceMarkedAsStable(inputObject) {
|
||||
return inputObject &&
|
||||
inputObject.metadata &&
|
||||
inputObject.metadata.labels &&
|
||||
inputObject.metadata.labels[exports.CANARY_VERSION_LABEL] == exports.STABLE_LABEL_VALUE;
|
||||
}
|
||||
exports.isResourceMarkedAsStable = isResourceMarkedAsStable;
|
||||
function getStableResource(inputObject) {
|
||||
var replicaCount = isSpecContainsReplicas(inputObject.kind) ? inputObject.metadata.replicas : 0;
|
||||
return getNewCanaryObject(inputObject, replicaCount, exports.STABLE_LABEL_VALUE);
|
||||
}
|
||||
exports.getStableResource = getStableResource;
|
||||
function getNewBaselineResource(stableObject, replicas) {
|
||||
return getNewCanaryObject(stableObject, replicas, exports.BASELINE_LABEL_VALUE);
|
||||
}
|
||||
exports.getNewBaselineResource = getNewBaselineResource;
|
||||
function getNewCanaryResource(inputObject, replicas) {
|
||||
return getNewCanaryObject(inputObject, replicas, exports.CANARY_LABEL_VALUE);
|
||||
}
|
||||
exports.getNewCanaryResource = getNewCanaryResource;
|
||||
function fetchCanaryResource(kubectl, kind, name) {
|
||||
return fetchResource(kubectl, kind, getCanaryResourceName(name));
|
||||
}
|
||||
exports.fetchCanaryResource = fetchCanaryResource;
|
||||
function fetchResource(kubectl, kind, name) {
|
||||
const result = kubectl.getResource(kind, name);
|
||||
if (result == null || !!result.stderr) {
|
||||
return null;
|
||||
}
|
||||
if (!!result.stdout) {
|
||||
const resource = JSON.parse(result.stdout);
|
||||
try {
|
||||
UnsetsClusterSpecficDetails(resource);
|
||||
return resource;
|
||||
}
|
||||
catch (ex) {
|
||||
core.debug('Exception occurred while Parsing ' + resource + ' in Json object');
|
||||
core.debug(`Exception:${ex}`);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
exports.fetchResource = fetchResource;
|
||||
function isCanaryDeploymentStrategy() {
|
||||
const deploymentStrategy = TaskInputParameters.deploymentStrategy;
|
||||
return deploymentStrategy && deploymentStrategy.toUpperCase() === exports.CANARY_DEPLOYMENT_STRATEGY;
|
||||
}
|
||||
exports.isCanaryDeploymentStrategy = isCanaryDeploymentStrategy;
|
||||
function isSMICanaryStrategy() {
|
||||
const deploymentStrategy = TaskInputParameters.trafficSplitMethod;
|
||||
return isCanaryDeploymentStrategy() && deploymentStrategy && deploymentStrategy.toUpperCase() === exports.TRAFFIC_SPLIT_STRATEGY;
|
||||
}
|
||||
exports.isSMICanaryStrategy = isSMICanaryStrategy;
|
||||
function getCanaryResourceName(name) {
|
||||
return name + CANARY_SUFFIX;
|
||||
}
|
||||
exports.getCanaryResourceName = getCanaryResourceName;
|
||||
function getBaselineResourceName(name) {
|
||||
return name + BASELINE_SUFFIX;
|
||||
}
|
||||
exports.getBaselineResourceName = getBaselineResourceName;
|
||||
function getStableResourceName(name) {
|
||||
return name + exports.STABLE_SUFFIX;
|
||||
}
|
||||
exports.getStableResourceName = getStableResourceName;
|
||||
function UnsetsClusterSpecficDetails(resource) {
|
||||
if (resource == null) {
|
||||
return;
|
||||
}
|
||||
// Unsets the cluster specific details in the object
|
||||
if (!!resource) {
|
||||
const metadata = resource.metadata;
|
||||
const status = resource.status;
|
||||
if (!!metadata) {
|
||||
const newMetadata = {
|
||||
'annotations': metadata.annotations,
|
||||
'labels': metadata.labels,
|
||||
'name': metadata.name
|
||||
};
|
||||
resource.metadata = newMetadata;
|
||||
}
|
||||
if (!!status) {
|
||||
resource.status = {};
|
||||
}
|
||||
}
|
||||
}
|
||||
function getNewCanaryObject(inputObject, replicas, type) {
|
||||
const newObject = JSON.parse(JSON.stringify(inputObject));
|
||||
// Updating name
|
||||
if (type === exports.CANARY_LABEL_VALUE) {
|
||||
newObject.metadata.name = getCanaryResourceName(inputObject.metadata.name);
|
||||
}
|
||||
else if (type === exports.STABLE_LABEL_VALUE) {
|
||||
newObject.metadata.name = getStableResourceName(inputObject.metadata.name);
|
||||
}
|
||||
else {
|
||||
newObject.metadata.name = getBaselineResourceName(inputObject.metadata.name);
|
||||
}
|
||||
// Adding labels and annotations.
|
||||
addCanaryLabelsAndAnnotations(newObject, type);
|
||||
// Updating no. of replicas
|
||||
if (isSpecContainsReplicas(newObject.kind)) {
|
||||
newObject.spec.replicas = replicas;
|
||||
}
|
||||
return newObject;
|
||||
}
|
||||
function isSpecContainsReplicas(kind) {
|
||||
return !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) &&
|
||||
!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase) &&
|
||||
!helper.isServiceEntity(kind);
|
||||
}
|
||||
function addCanaryLabelsAndAnnotations(inputObject, type) {
|
||||
const newLabels = new Map();
|
||||
newLabels[exports.CANARY_VERSION_LABEL] = type;
|
||||
helper.updateObjectLabels(inputObject, newLabels, false);
|
||||
helper.updateObjectAnnotations(inputObject, newLabels, false);
|
||||
helper.updateSelectorLabels(inputObject, newLabels, false);
|
||||
if (!helper.isServiceEntity(inputObject.kind)) {
|
||||
helper.updateSpecLabels(inputObject, newLabels, false);
|
||||
}
|
||||
}
|
||||
function cleanUpCanary(kubectl, files, includeServices) {
|
||||
var deleteObject = function (kind, name) {
|
||||
try {
|
||||
const result = kubectl.delete([kind, name]);
|
||||
utility_1.checkForErrors([result]);
|
||||
}
|
||||
catch (ex) {
|
||||
// Ignore failures of delete if doesn't exist
|
||||
}
|
||||
};
|
||||
files.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isDeploymentEntity(kind) || (includeServices && helper.isServiceEntity(kind))) {
|
||||
const canaryObjectName = getCanaryResourceName(name);
|
||||
const baselineObjectName = getBaselineResourceName(name);
|
||||
deleteObject(kind, canaryObjectName);
|
||||
deleteObject(kind, baselineObjectName);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,148 +1,163 @@
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getManifestFiles = exports.deploy = void 0;
|
||||
const fs = require("fs");
|
||||
const core = require("@actions/core");
|
||||
const yaml = require("js-yaml");
|
||||
const canaryDeploymentHelper = require("./canary-deployment-helper");
|
||||
const KubernetesObjectUtility = require("../resource-object-utility");
|
||||
const TaskInputParameters = require("../../input-parameters");
|
||||
const models = require("../../constants");
|
||||
const fileHelper = require("../files-helper");
|
||||
const utils = require("../manifest-utilities");
|
||||
const KubernetesManifestUtility = require("../manifest-stability-utility");
|
||||
const KubernetesConstants = require("../../constants");
|
||||
const manifest_utilities_1 = require("../manifest-utilities");
|
||||
const pod_canary_deployment_helper_1 = require("./pod-canary-deployment-helper");
|
||||
const smi_canary_deployment_helper_1 = require("./smi-canary-deployment-helper");
|
||||
const utility_1 = require("../utility");
|
||||
const blue_green_helper_1 = require("./blue-green-helper");
|
||||
const service_blue_green_helper_1 = require("./service-blue-green-helper");
|
||||
const ingress_blue_green_helper_1 = require("./ingress-blue-green-helper");
|
||||
const smi_blue_green_helper_1 = require("./smi-blue-green-helper");
|
||||
function deploy(kubectl, manifestFilePaths, deploymentStrategy) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
// get manifest files
|
||||
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(manifestFilePaths);
|
||||
// deployment
|
||||
const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy), blue_green_helper_1.isBlueGreenDeploymentStrategy());
|
||||
// check manifest stability
|
||||
const resourceTypes = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([KubernetesConstants.DiscoveryAndLoadBalancerResource.service]));
|
||||
yield checkManifestStability(kubectl, resourceTypes);
|
||||
// route blue-green deployments
|
||||
if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
|
||||
yield blue_green_helper_1.routeBlueGreen(kubectl, inputManifestFiles);
|
||||
}
|
||||
// print ingress resources
|
||||
const ingressResources = KubernetesObjectUtility.getResources(deployedManifestFiles, [KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress]);
|
||||
ingressResources.forEach(ingressResource => {
|
||||
kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress, ingressResource.name);
|
||||
});
|
||||
// annotate resources
|
||||
let allPods;
|
||||
try {
|
||||
allPods = JSON.parse((kubectl.getAllPods()).stdout);
|
||||
}
|
||||
catch (e) {
|
||||
core.debug("Unable to parse pods; Error: " + e);
|
||||
}
|
||||
annotateResources(deployedManifestFiles, kubectl, resourceTypes, allPods);
|
||||
});
|
||||
}
|
||||
exports.deploy = deploy;
|
||||
function getManifestFiles(manifestFilePaths) {
|
||||
const files = utils.getManifestFiles(manifestFilePaths);
|
||||
if (files == null || files.length === 0) {
|
||||
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
exports.getManifestFiles = getManifestFiles;
|
||||
function deployManifests(files, kubectl, isCanaryDeploymentStrategy, isBlueGreenDeploymentStrategy) {
|
||||
let result;
|
||||
if (isCanaryDeploymentStrategy) {
|
||||
let canaryDeploymentOutput;
|
||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||
canaryDeploymentOutput = smi_canary_deployment_helper_1.deploySMICanary(kubectl, files);
|
||||
}
|
||||
else {
|
||||
canaryDeploymentOutput = pod_canary_deployment_helper_1.deployPodCanary(kubectl, files);
|
||||
}
|
||||
result = canaryDeploymentOutput.result;
|
||||
files = canaryDeploymentOutput.newFilePaths;
|
||||
}
|
||||
else if (isBlueGreenDeploymentStrategy) {
|
||||
let blueGreenDeploymentOutput;
|
||||
if (blue_green_helper_1.isIngressRoute()) {
|
||||
blueGreenDeploymentOutput = ingress_blue_green_helper_1.deployBlueGreenIngress(kubectl, files);
|
||||
}
|
||||
else if (blue_green_helper_1.isSMIRoute()) {
|
||||
blueGreenDeploymentOutput = smi_blue_green_helper_1.deployBlueGreenSMI(kubectl, files);
|
||||
}
|
||||
else {
|
||||
blueGreenDeploymentOutput = service_blue_green_helper_1.deployBlueGreenService(kubectl, files);
|
||||
}
|
||||
result = blueGreenDeploymentOutput.result;
|
||||
files = blueGreenDeploymentOutput.newFilePaths;
|
||||
}
|
||||
else {
|
||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||
const updatedManifests = appendStableVersionLabelToResource(files, kubectl);
|
||||
result = kubectl.apply(updatedManifests, TaskInputParameters.forceDeployment);
|
||||
}
|
||||
else {
|
||||
result = kubectl.apply(files, TaskInputParameters.forceDeployment);
|
||||
}
|
||||
}
|
||||
utility_1.checkForErrors([result]);
|
||||
return files;
|
||||
}
|
||||
function appendStableVersionLabelToResource(files, kubectl) {
|
||||
const manifestFiles = [];
|
||||
const newObjectsList = [];
|
||||
files.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const kind = inputObject.kind;
|
||||
if (KubernetesObjectUtility.isDeploymentEntity(kind)) {
|
||||
const updatedObject = canaryDeploymentHelper.markResourceAsStable(inputObject);
|
||||
newObjectsList.push(updatedObject);
|
||||
}
|
||||
else {
|
||||
manifestFiles.push(filePath);
|
||||
}
|
||||
});
|
||||
});
|
||||
const updatedManifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
manifestFiles.push(...updatedManifestFiles);
|
||||
return manifestFiles;
|
||||
}
|
||||
function checkManifestStability(kubectl, resources) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
|
||||
});
|
||||
}
|
||||
function annotateResources(files, kubectl, resourceTypes, allPods) {
|
||||
const annotateResults = [];
|
||||
annotateResults.push(utility_1.annotateNamespace(kubectl, TaskInputParameters.namespace));
|
||||
annotateResults.push(kubectl.annotateFiles(files, models.workflowAnnotations, true));
|
||||
resourceTypes.forEach(resource => {
|
||||
if (resource.type.toUpperCase() !== models.KubernetesWorkload.pod.toUpperCase()) {
|
||||
utility_1.annotateChildPods(kubectl, resource.type, resource.name, allPods)
|
||||
.forEach(execResult => annotateResults.push(execResult));
|
||||
}
|
||||
});
|
||||
utility_1.checkForErrors(annotateResults, true);
|
||||
}
|
||||
function isCanaryDeploymentStrategy(deploymentStrategy) {
|
||||
return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase();
|
||||
}
|
||||
'use strict';
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getManifestFiles = exports.deploy = void 0;
|
||||
const fs = require("fs");
|
||||
const core = require("@actions/core");
|
||||
const yaml = require("js-yaml");
|
||||
const canaryDeploymentHelper = require("./canary-deployment-helper");
|
||||
const KubernetesObjectUtility = require("../resource-object-utility");
|
||||
const TaskInputParameters = require("../../input-parameters");
|
||||
const models = require("../../constants");
|
||||
const fileHelper = require("../files-helper");
|
||||
const utils = require("../manifest-utilities");
|
||||
const KubernetesManifestUtility = require("../manifest-stability-utility");
|
||||
const KubernetesConstants = require("../../constants");
|
||||
const manifest_utilities_1 = require("../manifest-utilities");
|
||||
const pod_canary_deployment_helper_1 = require("./pod-canary-deployment-helper");
|
||||
const smi_canary_deployment_helper_1 = require("./smi-canary-deployment-helper");
|
||||
const utility_1 = require("../utility");
|
||||
const blue_green_helper_1 = require("./blue-green-helper");
|
||||
const service_blue_green_helper_1 = require("./service-blue-green-helper");
|
||||
const ingress_blue_green_helper_1 = require("./ingress-blue-green-helper");
|
||||
const smi_blue_green_helper_1 = require("./smi-blue-green-helper");
|
||||
function deploy(kubectl, manifestFilePaths, deploymentStrategy) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
// get manifest files
|
||||
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(manifestFilePaths);
|
||||
// deployment
|
||||
const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy), blue_green_helper_1.isBlueGreenDeploymentStrategy());
|
||||
// check manifest stability
|
||||
const resourceTypes = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([KubernetesConstants.DiscoveryAndLoadBalancerResource.service]));
|
||||
yield checkManifestStability(kubectl, resourceTypes);
|
||||
// route blue-green deployments
|
||||
if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
|
||||
yield blue_green_helper_1.routeBlueGreen(kubectl, inputManifestFiles);
|
||||
}
|
||||
// print ingress resources
|
||||
const ingressResources = KubernetesObjectUtility.getResources(deployedManifestFiles, [KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress]);
|
||||
ingressResources.forEach(ingressResource => {
|
||||
kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress, ingressResource.name);
|
||||
});
|
||||
// annotate resources
|
||||
let allPods;
|
||||
try {
|
||||
allPods = JSON.parse((kubectl.getAllPods()).stdout);
|
||||
}
|
||||
catch (e) {
|
||||
core.debug("Unable to parse pods; Error: " + e);
|
||||
}
|
||||
annotateAndLabelResources(deployedManifestFiles, kubectl, resourceTypes, allPods);
|
||||
});
|
||||
}
|
||||
exports.deploy = deploy;
|
||||
function getManifestFiles(manifestFilePaths) {
|
||||
const files = utils.getManifestFiles(manifestFilePaths);
|
||||
if (files == null || files.length === 0) {
|
||||
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
exports.getManifestFiles = getManifestFiles;
|
||||
function deployManifests(files, kubectl, isCanaryDeploymentStrategy, isBlueGreenDeploymentStrategy) {
|
||||
let result;
|
||||
if (isCanaryDeploymentStrategy) {
|
||||
let canaryDeploymentOutput;
|
||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||
canaryDeploymentOutput = smi_canary_deployment_helper_1.deploySMICanary(kubectl, files);
|
||||
}
|
||||
else {
|
||||
canaryDeploymentOutput = pod_canary_deployment_helper_1.deployPodCanary(kubectl, files);
|
||||
}
|
||||
result = canaryDeploymentOutput.result;
|
||||
files = canaryDeploymentOutput.newFilePaths;
|
||||
}
|
||||
else if (isBlueGreenDeploymentStrategy) {
|
||||
let blueGreenDeploymentOutput;
|
||||
if (blue_green_helper_1.isIngressRoute()) {
|
||||
blueGreenDeploymentOutput = ingress_blue_green_helper_1.deployBlueGreenIngress(kubectl, files);
|
||||
}
|
||||
else if (blue_green_helper_1.isSMIRoute()) {
|
||||
blueGreenDeploymentOutput = smi_blue_green_helper_1.deployBlueGreenSMI(kubectl, files);
|
||||
}
|
||||
else {
|
||||
blueGreenDeploymentOutput = service_blue_green_helper_1.deployBlueGreenService(kubectl, files);
|
||||
}
|
||||
result = blueGreenDeploymentOutput.result;
|
||||
files = blueGreenDeploymentOutput.newFilePaths;
|
||||
}
|
||||
else {
|
||||
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
|
||||
const updatedManifests = appendStableVersionLabelToResource(files, kubectl);
|
||||
result = kubectl.apply(updatedManifests, TaskInputParameters.forceDeployment);
|
||||
}
|
||||
else {
|
||||
result = kubectl.apply(files, TaskInputParameters.forceDeployment);
|
||||
}
|
||||
}
|
||||
utility_1.checkForErrors([result]);
|
||||
return files;
|
||||
}
|
||||
function appendStableVersionLabelToResource(files, kubectl) {
|
||||
const manifestFiles = [];
|
||||
const newObjectsList = [];
|
||||
files.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const kind = inputObject.kind;
|
||||
if (KubernetesObjectUtility.isDeploymentEntity(kind)) {
|
||||
const updatedObject = canaryDeploymentHelper.markResourceAsStable(inputObject);
|
||||
newObjectsList.push(updatedObject);
|
||||
}
|
||||
else {
|
||||
manifestFiles.push(filePath);
|
||||
}
|
||||
});
|
||||
});
|
||||
const updatedManifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
manifestFiles.push(...updatedManifestFiles);
|
||||
return manifestFiles;
|
||||
}
|
||||
function checkManifestStability(kubectl, resources) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
|
||||
});
|
||||
}
|
||||
function annotateAndLabelResources(files, kubectl, resourceTypes, allPods) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const workflowFilePath = yield utility_1.getWorkflowFilePath(TaskInputParameters.githubToken);
|
||||
const deploymentConfig = yield utility_1.getDeploymentConfig();
|
||||
const annotationKeyLabel = models.getWorkflowAnnotationKeyLabel(workflowFilePath);
|
||||
annotateResources(files, kubectl, resourceTypes, allPods, annotationKeyLabel, workflowFilePath, deploymentConfig);
|
||||
labelResources(files, kubectl, annotationKeyLabel);
|
||||
});
|
||||
}
|
||||
function annotateResources(files, kubectl, resourceTypes, allPods, annotationKey, workflowFilePath, deploymentConfig) {
|
||||
const annotateResults = [];
|
||||
const lastSuccessSha = utility_1.getLastSuccessfulRunSha(kubectl, TaskInputParameters.namespace, annotationKey);
|
||||
let annotationKeyValStr = annotationKey + '=' + models.getWorkflowAnnotationsJson(lastSuccessSha, workflowFilePath, deploymentConfig);
|
||||
annotateResults.push(kubectl.annotate('namespace', TaskInputParameters.namespace, annotationKeyValStr));
|
||||
annotateResults.push(kubectl.annotateFiles(files, annotationKeyValStr));
|
||||
resourceTypes.forEach(resource => {
|
||||
if (resource.type.toUpperCase() !== models.KubernetesWorkload.pod.toUpperCase()) {
|
||||
utility_1.annotateChildPods(kubectl, resource.type, resource.name, annotationKeyValStr, allPods)
|
||||
.forEach(execResult => annotateResults.push(execResult));
|
||||
}
|
||||
});
|
||||
utility_1.checkForErrors(annotateResults, true);
|
||||
}
|
||||
function labelResources(files, kubectl, label) {
|
||||
const labels = [`workflowFriendlyName=${utility_1.normaliseWorkflowStrLabel(process.env.GITHUB_WORKFLOW)}`, `workflow=${label}`];
|
||||
utility_1.checkForErrors([kubectl.labelFiles(files, labels)], true);
|
||||
}
|
||||
function isCanaryDeploymentStrategy(deploymentStrategy) {
|
||||
return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase();
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ exports.rejectBlueGreenIngress = rejectBlueGreenIngress;
|
||||
function routeBlueGreenIngress(kubectl, nextLabel, serviceNameMap, ingressEntityList) {
|
||||
let newObjectsList = [];
|
||||
if (!nextLabel) {
|
||||
newObjectsList = newObjectsList.concat(ingressEntityList);
|
||||
newObjectsList = ingressEntityList.filter(ingress => isIngressRouted(ingress, serviceNameMap));
|
||||
}
|
||||
else {
|
||||
ingressEntityList.forEach((inputObject) => {
|
||||
|
||||
@@ -1,58 +1,58 @@
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.deployPodCanary = void 0;
|
||||
const core = require("@actions/core");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const TaskInputParameters = require("../../input-parameters");
|
||||
const fileHelper = require("../files-helper");
|
||||
const helper = require("../resource-object-utility");
|
||||
const canaryDeploymentHelper = require("./canary-deployment-helper");
|
||||
function deployPodCanary(kubectl, filePaths) {
|
||||
const newObjectsList = [];
|
||||
const percentage = parseInt(TaskInputParameters.canaryPercentage);
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isDeploymentEntity(kind)) {
|
||||
core.debug('Calculating replica count for canary');
|
||||
const canaryReplicaCount = calculateReplicaCountForCanary(inputObject, percentage);
|
||||
core.debug('Replica count is ' + canaryReplicaCount);
|
||||
// Get stable object
|
||||
core.debug('Querying stable object');
|
||||
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name);
|
||||
if (!stableObject) {
|
||||
core.debug('Stable object not found. Creating only canary object');
|
||||
// If stable object not found, create canary deployment.
|
||||
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
|
||||
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
|
||||
newObjectsList.push(newCanaryObject);
|
||||
}
|
||||
else {
|
||||
core.debug('Stable object found. Creating canary and baseline objects');
|
||||
// If canary object not found, create canary and baseline object.
|
||||
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
|
||||
const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount);
|
||||
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
|
||||
core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject));
|
||||
newObjectsList.push(newCanaryObject);
|
||||
newObjectsList.push(newBaselineObject);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Updating non deployment entity as it is.
|
||||
newObjectsList.push(inputObject);
|
||||
}
|
||||
});
|
||||
});
|
||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
|
||||
return { 'result': result, 'newFilePaths': manifestFiles };
|
||||
}
|
||||
exports.deployPodCanary = deployPodCanary;
|
||||
function calculateReplicaCountForCanary(inputObject, percentage) {
|
||||
const inputReplicaCount = helper.getReplicaCount(inputObject);
|
||||
return Math.round((inputReplicaCount * percentage) / 100);
|
||||
}
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.deployPodCanary = void 0;
|
||||
const core = require("@actions/core");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const TaskInputParameters = require("../../input-parameters");
|
||||
const fileHelper = require("../files-helper");
|
||||
const helper = require("../resource-object-utility");
|
||||
const canaryDeploymentHelper = require("./canary-deployment-helper");
|
||||
function deployPodCanary(kubectl, filePaths) {
|
||||
const newObjectsList = [];
|
||||
const percentage = parseInt(TaskInputParameters.canaryPercentage);
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isDeploymentEntity(kind)) {
|
||||
core.debug('Calculating replica count for canary');
|
||||
const canaryReplicaCount = calculateReplicaCountForCanary(inputObject, percentage);
|
||||
core.debug('Replica count is ' + canaryReplicaCount);
|
||||
// Get stable object
|
||||
core.debug('Querying stable object');
|
||||
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name);
|
||||
if (!stableObject) {
|
||||
core.debug('Stable object not found. Creating only canary object');
|
||||
// If stable object not found, create canary deployment.
|
||||
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
|
||||
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
|
||||
newObjectsList.push(newCanaryObject);
|
||||
}
|
||||
else {
|
||||
core.debug('Stable object found. Creating canary and baseline objects');
|
||||
// If canary object not found, create canary and baseline object.
|
||||
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
|
||||
const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount);
|
||||
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
|
||||
core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject));
|
||||
newObjectsList.push(newCanaryObject);
|
||||
newObjectsList.push(newBaselineObject);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Updating non deployment entity as it is.
|
||||
newObjectsList.push(inputObject);
|
||||
}
|
||||
});
|
||||
});
|
||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
|
||||
return { 'result': result, 'newFilePaths': manifestFiles };
|
||||
}
|
||||
exports.deployPodCanary = deployPodCanary;
|
||||
function calculateReplicaCountForCanary(inputObject, percentage) {
|
||||
const inputReplicaCount = helper.getReplicaCount(inputObject);
|
||||
return Math.round((inputReplicaCount * percentage) / 100);
|
||||
}
|
||||
|
||||
@@ -174,9 +174,9 @@ exports.validateTrafficSplitsState = validateTrafficSplitsState;
|
||||
function cleanupSMI(kubectl, serviceEntityList) {
|
||||
const deleteList = [];
|
||||
serviceEntityList.forEach((serviceObject) => {
|
||||
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX), kind: TRAFFIC_SPLIT_OBJECT });
|
||||
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, blue_green_helper_2.GREEN_SUFFIX), kind: serviceObject.kind });
|
||||
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, blue_green_helper_2.STABLE_SUFFIX), kind: serviceObject.kind });
|
||||
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX), kind: TRAFFIC_SPLIT_OBJECT });
|
||||
});
|
||||
// deleting all objects
|
||||
blue_green_helper_1.deleteObjects(kubectl, deleteList);
|
||||
|
||||
@@ -1,199 +1,196 @@
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.redirectTrafficToStableDeployment = exports.redirectTrafficToCanaryDeployment = exports.deploySMICanary = void 0;
|
||||
const core = require("@actions/core");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const util = require("util");
|
||||
const TaskInputParameters = require("../../input-parameters");
|
||||
const fileHelper = require("../files-helper");
|
||||
const helper = require("../resource-object-utility");
|
||||
const utils = require("../manifest-utilities");
|
||||
const kubectlUtils = require("../kubectl-util");
|
||||
const canaryDeploymentHelper = require("./canary-deployment-helper");
|
||||
const utility_1 = require("../utility");
|
||||
const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-workflow-rollout';
|
||||
const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit';
|
||||
let trafficSplitAPIVersion = "";
|
||||
function deploySMICanary(kubectl, filePaths) {
|
||||
const newObjectsList = [];
|
||||
const canaryReplicaCount = parseInt(TaskInputParameters.baselineAndCanaryReplicas);
|
||||
core.debug('Replica count is ' + canaryReplicaCount);
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isDeploymentEntity(kind)) {
|
||||
// Get stable object
|
||||
core.debug('Querying stable object');
|
||||
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name);
|
||||
if (!stableObject) {
|
||||
core.debug('Stable object not found. Creating only canary object');
|
||||
// If stable object not found, create canary deployment.
|
||||
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
|
||||
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
|
||||
newObjectsList.push(newCanaryObject);
|
||||
}
|
||||
else {
|
||||
if (!canaryDeploymentHelper.isResourceMarkedAsStable(stableObject)) {
|
||||
throw (`StableSpecSelectorNotExist : ${name}`);
|
||||
}
|
||||
core.debug('Stable object found. Creating canary and baseline objects');
|
||||
// If canary object not found, create canary and baseline object.
|
||||
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
|
||||
const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount);
|
||||
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
|
||||
core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject));
|
||||
newObjectsList.push(newCanaryObject);
|
||||
newObjectsList.push(newBaselineObject);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Updating non deployment entity as it is.
|
||||
newObjectsList.push(inputObject);
|
||||
}
|
||||
});
|
||||
});
|
||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
|
||||
createCanaryService(kubectl, filePaths);
|
||||
return { 'result': result, 'newFilePaths': manifestFiles };
|
||||
}
|
||||
exports.deploySMICanary = deploySMICanary;
|
||||
function createCanaryService(kubectl, filePaths) {
|
||||
const newObjectsList = [];
|
||||
const trafficObjectsList = [];
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isServiceEntity(kind)) {
|
||||
const newCanaryServiceObject = canaryDeploymentHelper.getNewCanaryResource(inputObject);
|
||||
core.debug('New canary service object is: ' + JSON.stringify(newCanaryServiceObject));
|
||||
newObjectsList.push(newCanaryServiceObject);
|
||||
const newBaselineServiceObject = canaryDeploymentHelper.getNewBaselineResource(inputObject);
|
||||
core.debug('New baseline object is: ' + JSON.stringify(newBaselineServiceObject));
|
||||
newObjectsList.push(newBaselineServiceObject);
|
||||
core.debug('Querying for stable service object');
|
||||
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, canaryDeploymentHelper.getStableResourceName(name));
|
||||
if (!stableObject) {
|
||||
const newStableServiceObject = canaryDeploymentHelper.getStableResource(inputObject);
|
||||
core.debug('New stable service object is: ' + JSON.stringify(newStableServiceObject));
|
||||
newObjectsList.push(newStableServiceObject);
|
||||
core.debug('Creating the traffic object for service: ' + name);
|
||||
const trafficObject = createTrafficSplitManifestFile(kubectl, name, 0, 0, 1000);
|
||||
core.debug('Creating the traffic object for service: ' + trafficObject);
|
||||
trafficObjectsList.push(trafficObject);
|
||||
}
|
||||
else {
|
||||
let updateTrafficObject = true;
|
||||
const trafficObject = canaryDeploymentHelper.fetchResource(kubectl, TRAFFIC_SPLIT_OBJECT, getTrafficSplitResourceName(name));
|
||||
if (trafficObject) {
|
||||
const trafficJObject = JSON.parse(JSON.stringify(trafficObject));
|
||||
if (trafficJObject && trafficJObject.spec && trafficJObject.spec.backends) {
|
||||
trafficJObject.spec.backends.forEach((s) => {
|
||||
if (s.service === canaryDeploymentHelper.getCanaryResourceName(name) && s.weight === "1000m") {
|
||||
core.debug('Update traffic objcet not required');
|
||||
updateTrafficObject = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if (updateTrafficObject) {
|
||||
core.debug('Stable service object present so updating the traffic object for service: ' + name);
|
||||
trafficObjectsList.push(updateTrafficSplitObject(kubectl, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
manifestFiles.push(...trafficObjectsList);
|
||||
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
|
||||
utility_1.checkForErrors([result]);
|
||||
}
|
||||
function redirectTrafficToCanaryDeployment(kubectl, manifestFilePaths) {
|
||||
adjustTraffic(kubectl, manifestFilePaths, 0, 1000);
|
||||
}
|
||||
exports.redirectTrafficToCanaryDeployment = redirectTrafficToCanaryDeployment;
|
||||
function redirectTrafficToStableDeployment(kubectl, manifestFilePaths) {
|
||||
adjustTraffic(kubectl, manifestFilePaths, 1000, 0);
|
||||
}
|
||||
exports.redirectTrafficToStableDeployment = redirectTrafficToStableDeployment;
|
||||
function adjustTraffic(kubectl, manifestFilePaths, stableWeight, canaryWeight) {
|
||||
// get manifest files
|
||||
const inputManifestFiles = utils.getManifestFiles(manifestFilePaths);
|
||||
if (inputManifestFiles == null || inputManifestFiles.length == 0) {
|
||||
return;
|
||||
}
|
||||
const trafficSplitManifests = [];
|
||||
const serviceObjects = [];
|
||||
inputManifestFiles.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isServiceEntity(kind)) {
|
||||
trafficSplitManifests.push(createTrafficSplitManifestFile(kubectl, name, stableWeight, 0, canaryWeight));
|
||||
serviceObjects.push(name);
|
||||
}
|
||||
});
|
||||
});
|
||||
if (trafficSplitManifests.length <= 0) {
|
||||
return;
|
||||
}
|
||||
const result = kubectl.apply(trafficSplitManifests, TaskInputParameters.forceDeployment);
|
||||
core.debug('serviceObjects:' + serviceObjects.join(',') + ' result:' + result);
|
||||
utility_1.checkForErrors([result]);
|
||||
}
|
||||
function updateTrafficSplitObject(kubectl, serviceName) {
|
||||
const percentage = parseInt(TaskInputParameters.canaryPercentage) * 10;
|
||||
const baselineAndCanaryWeight = percentage / 2;
|
||||
const stableDeploymentWeight = 1000 - percentage;
|
||||
core.debug('Creating the traffic object with canary weight: ' + baselineAndCanaryWeight + ',baseling weight: ' + baselineAndCanaryWeight + ',stable: ' + stableDeploymentWeight);
|
||||
return createTrafficSplitManifestFile(kubectl, serviceName, stableDeploymentWeight, baselineAndCanaryWeight, baselineAndCanaryWeight);
|
||||
}
|
||||
function createTrafficSplitManifestFile(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight) {
|
||||
const smiObjectString = getTrafficSplitObject(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight);
|
||||
const manifestFile = fileHelper.writeManifestToFile(smiObjectString, TRAFFIC_SPLIT_OBJECT, serviceName);
|
||||
if (!manifestFile) {
|
||||
throw new Error('UnableToCreateTrafficSplitManifestFile');
|
||||
}
|
||||
return manifestFile;
|
||||
}
|
||||
function getTrafficSplitObject(kubectl, name, stableWeight, baselineWeight, canaryWeight) {
|
||||
if (!trafficSplitAPIVersion) {
|
||||
trafficSplitAPIVersion = kubectlUtils.getTrafficSplitAPIVersion(kubectl);
|
||||
}
|
||||
const trafficSplitObjectJson = `{
|
||||
'use strict';
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.redirectTrafficToStableDeployment = exports.redirectTrafficToCanaryDeployment = exports.deploySMICanary = void 0;
|
||||
const core = require("@actions/core");
|
||||
const fs = require("fs");
|
||||
const yaml = require("js-yaml");
|
||||
const TaskInputParameters = require("../../input-parameters");
|
||||
const fileHelper = require("../files-helper");
|
||||
const helper = require("../resource-object-utility");
|
||||
const utils = require("../manifest-utilities");
|
||||
const kubectlUtils = require("../kubectl-util");
|
||||
const canaryDeploymentHelper = require("./canary-deployment-helper");
|
||||
const utility_1 = require("../utility");
|
||||
const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-workflow-rollout';
|
||||
const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit';
|
||||
let trafficSplitAPIVersion = "";
|
||||
function deploySMICanary(kubectl, filePaths) {
|
||||
const newObjectsList = [];
|
||||
const canaryReplicaCount = parseInt(TaskInputParameters.baselineAndCanaryReplicas);
|
||||
core.debug('Replica count is ' + canaryReplicaCount);
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isDeploymentEntity(kind)) {
|
||||
// Get stable object
|
||||
core.debug('Querying stable object');
|
||||
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name);
|
||||
if (!stableObject) {
|
||||
core.debug('Stable object not found. Creating only canary object');
|
||||
// If stable object not found, create canary deployment.
|
||||
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
|
||||
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
|
||||
newObjectsList.push(newCanaryObject);
|
||||
}
|
||||
else {
|
||||
if (!canaryDeploymentHelper.isResourceMarkedAsStable(stableObject)) {
|
||||
throw (`StableSpecSelectorNotExist : ${name}`);
|
||||
}
|
||||
core.debug('Stable object found. Creating canary and baseline objects');
|
||||
// If canary object not found, create canary and baseline object.
|
||||
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
|
||||
const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount);
|
||||
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
|
||||
core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject));
|
||||
newObjectsList.push(newCanaryObject);
|
||||
newObjectsList.push(newBaselineObject);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Updating non deployment entity as it is.
|
||||
newObjectsList.push(inputObject);
|
||||
}
|
||||
});
|
||||
});
|
||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
|
||||
createCanaryService(kubectl, filePaths);
|
||||
return { 'result': result, 'newFilePaths': manifestFiles };
|
||||
}
|
||||
exports.deploySMICanary = deploySMICanary;
|
||||
function createCanaryService(kubectl, filePaths) {
|
||||
const newObjectsList = [];
|
||||
const trafficObjectsList = [];
|
||||
filePaths.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isServiceEntity(kind)) {
|
||||
const newCanaryServiceObject = canaryDeploymentHelper.getNewCanaryResource(inputObject);
|
||||
core.debug('New canary service object is: ' + JSON.stringify(newCanaryServiceObject));
|
||||
newObjectsList.push(newCanaryServiceObject);
|
||||
const newBaselineServiceObject = canaryDeploymentHelper.getNewBaselineResource(inputObject);
|
||||
core.debug('New baseline object is: ' + JSON.stringify(newBaselineServiceObject));
|
||||
newObjectsList.push(newBaselineServiceObject);
|
||||
core.debug('Querying for stable service object');
|
||||
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, canaryDeploymentHelper.getStableResourceName(name));
|
||||
if (!stableObject) {
|
||||
const newStableServiceObject = canaryDeploymentHelper.getStableResource(inputObject);
|
||||
core.debug('New stable service object is: ' + JSON.stringify(newStableServiceObject));
|
||||
newObjectsList.push(newStableServiceObject);
|
||||
core.debug('Creating the traffic object for service: ' + name);
|
||||
const trafficObject = createTrafficSplitManifestFile(kubectl, name, 0, 0, 1000);
|
||||
core.debug('Creating the traffic object for service: ' + trafficObject);
|
||||
trafficObjectsList.push(trafficObject);
|
||||
}
|
||||
else {
|
||||
let updateTrafficObject = true;
|
||||
const trafficObject = canaryDeploymentHelper.fetchResource(kubectl, TRAFFIC_SPLIT_OBJECT, getTrafficSplitResourceName(name));
|
||||
if (trafficObject) {
|
||||
const trafficJObject = JSON.parse(JSON.stringify(trafficObject));
|
||||
if (trafficJObject && trafficJObject.spec && trafficJObject.spec.backends) {
|
||||
trafficJObject.spec.backends.forEach((s) => {
|
||||
if (s.service === canaryDeploymentHelper.getCanaryResourceName(name) && s.weight === "1000m") {
|
||||
core.debug('Update traffic objcet not required');
|
||||
updateTrafficObject = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if (updateTrafficObject) {
|
||||
core.debug('Stable service object present so updating the traffic object for service: ' + name);
|
||||
trafficObjectsList.push(updateTrafficSplitObject(kubectl, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
|
||||
manifestFiles.push(...trafficObjectsList);
|
||||
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
|
||||
utility_1.checkForErrors([result]);
|
||||
}
|
||||
function redirectTrafficToCanaryDeployment(kubectl, manifestFilePaths) {
|
||||
adjustTraffic(kubectl, manifestFilePaths, 0, 1000);
|
||||
}
|
||||
exports.redirectTrafficToCanaryDeployment = redirectTrafficToCanaryDeployment;
|
||||
function redirectTrafficToStableDeployment(kubectl, manifestFilePaths) {
|
||||
adjustTraffic(kubectl, manifestFilePaths, 1000, 0);
|
||||
}
|
||||
exports.redirectTrafficToStableDeployment = redirectTrafficToStableDeployment;
|
||||
function adjustTraffic(kubectl, manifestFilePaths, stableWeight, canaryWeight) {
|
||||
// get manifest files
|
||||
const inputManifestFiles = utils.getManifestFiles(manifestFilePaths);
|
||||
if (inputManifestFiles == null || inputManifestFiles.length == 0) {
|
||||
return;
|
||||
}
|
||||
const trafficSplitManifests = [];
|
||||
const serviceObjects = [];
|
||||
inputManifestFiles.forEach((filePath) => {
|
||||
const fileContents = fs.readFileSync(filePath);
|
||||
yaml.safeLoadAll(fileContents, function (inputObject) {
|
||||
const name = inputObject.metadata.name;
|
||||
const kind = inputObject.kind;
|
||||
if (helper.isServiceEntity(kind)) {
|
||||
trafficSplitManifests.push(createTrafficSplitManifestFile(kubectl, name, stableWeight, 0, canaryWeight));
|
||||
serviceObjects.push(name);
|
||||
}
|
||||
});
|
||||
});
|
||||
if (trafficSplitManifests.length <= 0) {
|
||||
return;
|
||||
}
|
||||
const result = kubectl.apply(trafficSplitManifests, TaskInputParameters.forceDeployment);
|
||||
core.debug('serviceObjects:' + serviceObjects.join(',') + ' result:' + result);
|
||||
utility_1.checkForErrors([result]);
|
||||
}
|
||||
function updateTrafficSplitObject(kubectl, serviceName) {
|
||||
const percentage = parseInt(TaskInputParameters.canaryPercentage) * 10;
|
||||
const baselineAndCanaryWeight = percentage / 2;
|
||||
const stableDeploymentWeight = 1000 - percentage;
|
||||
core.debug('Creating the traffic object with canary weight: ' + baselineAndCanaryWeight + ',baseling weight: ' + baselineAndCanaryWeight + ',stable: ' + stableDeploymentWeight);
|
||||
return createTrafficSplitManifestFile(kubectl, serviceName, stableDeploymentWeight, baselineAndCanaryWeight, baselineAndCanaryWeight);
|
||||
}
|
||||
function createTrafficSplitManifestFile(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight) {
|
||||
const smiObjectString = getTrafficSplitObject(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight);
|
||||
const manifestFile = fileHelper.writeManifestToFile(smiObjectString, TRAFFIC_SPLIT_OBJECT, serviceName);
|
||||
if (!manifestFile) {
|
||||
throw new Error('UnableToCreateTrafficSplitManifestFile');
|
||||
}
|
||||
return manifestFile;
|
||||
}
|
||||
function getTrafficSplitObject(kubectl, name, stableWeight, baselineWeight, canaryWeight) {
|
||||
if (!trafficSplitAPIVersion) {
|
||||
trafficSplitAPIVersion = kubectlUtils.getTrafficSplitAPIVersion(kubectl);
|
||||
}
|
||||
return `{
|
||||
"apiVersion": "${trafficSplitAPIVersion}",
|
||||
"kind": "TrafficSplit",
|
||||
"metadata": {
|
||||
"name": "%s"
|
||||
"name": "${getTrafficSplitResourceName(name)}"
|
||||
},
|
||||
"spec": {
|
||||
"backends": [
|
||||
{
|
||||
"service": "%s",
|
||||
"weight": "%sm"
|
||||
"service": "${canaryDeploymentHelper.getStableResourceName(name)}",
|
||||
"weight": "${stableWeight}"
|
||||
},
|
||||
{
|
||||
"service": "%s",
|
||||
"weight": "%sm"
|
||||
"service": "${canaryDeploymentHelper.getBaselineResourceName(name)}",
|
||||
"weight": "${baselineWeight}"
|
||||
},
|
||||
{
|
||||
"service": "%s",
|
||||
"weight": "%sm"
|
||||
"service": "${canaryDeploymentHelper.getCanaryResourceName(name)}",
|
||||
"weight": "${canaryWeight}"
|
||||
}
|
||||
],
|
||||
"service": "%s"
|
||||
"service": "${name}"
|
||||
}
|
||||
}`;
|
||||
const trafficSplitObject = util.format(trafficSplitObjectJson, getTrafficSplitResourceName(name), canaryDeploymentHelper.getStableResourceName(name), stableWeight, canaryDeploymentHelper.getBaselineResourceName(name), baselineWeight, canaryDeploymentHelper.getCanaryResourceName(name), canaryWeight, name);
|
||||
return trafficSplitObject;
|
||||
}
|
||||
function getTrafficSplitResourceName(name) {
|
||||
return name + TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX;
|
||||
}
|
||||
}`;
|
||||
}
|
||||
function getTrafficSplitResourceName(name) {
|
||||
return name + TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX;
|
||||
}
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isEqual = exports.StringComparer = void 0;
|
||||
var StringComparer;
|
||||
(function (StringComparer) {
|
||||
StringComparer[StringComparer["Ordinal"] = 0] = "Ordinal";
|
||||
StringComparer[StringComparer["OrdinalIgnoreCase"] = 1] = "OrdinalIgnoreCase";
|
||||
})(StringComparer = exports.StringComparer || (exports.StringComparer = {}));
|
||||
function isEqual(str1, str2, stringComparer) {
|
||||
if (str1 == null && str2 == null) {
|
||||
return true;
|
||||
}
|
||||
if (str1 == null) {
|
||||
return false;
|
||||
}
|
||||
if (str2 == null) {
|
||||
return false;
|
||||
}
|
||||
if (stringComparer == StringComparer.OrdinalIgnoreCase) {
|
||||
return str1.toUpperCase() === str2.toUpperCase();
|
||||
}
|
||||
else {
|
||||
return str1 === str2;
|
||||
}
|
||||
}
|
||||
exports.isEqual = isEqual;
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isEqual = exports.StringComparer = void 0;
|
||||
var StringComparer;
|
||||
(function (StringComparer) {
|
||||
StringComparer[StringComparer["Ordinal"] = 0] = "Ordinal";
|
||||
StringComparer[StringComparer["OrdinalIgnoreCase"] = 1] = "OrdinalIgnoreCase";
|
||||
})(StringComparer = exports.StringComparer || (exports.StringComparer = {}));
|
||||
function isEqual(str1, str2, stringComparer) {
|
||||
if (str1 == null && str2 == null) {
|
||||
return true;
|
||||
}
|
||||
if (str1 == null) {
|
||||
return false;
|
||||
}
|
||||
if (str2 == null) {
|
||||
return false;
|
||||
}
|
||||
if (stringComparer == StringComparer.OrdinalIgnoreCase) {
|
||||
return str1.toUpperCase() === str2.toUpperCase();
|
||||
}
|
||||
else {
|
||||
return str1 === str2;
|
||||
}
|
||||
}
|
||||
exports.isEqual = isEqual;
|
||||
|
||||
+527
-527
File diff suppressed because it is too large
Load Diff
+228
-108
@@ -1,108 +1,228 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.annotateNamespace = exports.annotateChildPods = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0;
|
||||
const os = require("os");
|
||||
const core = require("@actions/core");
|
||||
const constants_1 = require("../constants");
|
||||
function getExecutableExtension() {
|
||||
if (os.type().match(/^Win/)) {
|
||||
return '.exe';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
exports.getExecutableExtension = getExecutableExtension;
|
||||
function isEqual(str1, str2, ignoreCase) {
|
||||
if (str1 == null && str2 == null) {
|
||||
return true;
|
||||
}
|
||||
if (str1 == null || str2 == null) {
|
||||
return false;
|
||||
}
|
||||
if (ignoreCase) {
|
||||
return str1.toUpperCase() === str2.toUpperCase();
|
||||
}
|
||||
else {
|
||||
return str1 === str2;
|
||||
}
|
||||
}
|
||||
exports.isEqual = isEqual;
|
||||
function checkForErrors(execResults, warnIfError) {
|
||||
if (execResults.length !== 0) {
|
||||
let stderr = '';
|
||||
execResults.forEach(result => {
|
||||
if (result && result.stderr) {
|
||||
if (result.code !== 0) {
|
||||
stderr += result.stderr + '\n';
|
||||
}
|
||||
else {
|
||||
core.warning(result.stderr);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (stderr.length > 0) {
|
||||
if (warnIfError) {
|
||||
core.warning(stderr.trim());
|
||||
}
|
||||
else {
|
||||
throw new Error(stderr.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.checkForErrors = checkForErrors;
|
||||
function annotateChildPods(kubectl, resourceType, resourceName, allPods) {
|
||||
const commandExecutionResults = [];
|
||||
let owner = resourceName;
|
||||
if (resourceType.toLowerCase().indexOf('deployment') > -1) {
|
||||
owner = kubectl.getNewReplicaSet(resourceName);
|
||||
}
|
||||
if (allPods && allPods.items && allPods.items.length > 0) {
|
||||
allPods.items.forEach((pod) => {
|
||||
const owners = pod.metadata.ownerReferences;
|
||||
if (owners) {
|
||||
for (let ownerRef of owners) {
|
||||
if (ownerRef.name === owner) {
|
||||
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, constants_1.workflowAnnotations, true));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return commandExecutionResults;
|
||||
}
|
||||
exports.annotateChildPods = annotateChildPods;
|
||||
function annotateNamespace(kubectl, namespaceName) {
|
||||
const result = kubectl.getResource('namespace', namespaceName);
|
||||
if (!result) {
|
||||
return { code: 1, stderr: 'Failed to get resource' };
|
||||
}
|
||||
else {
|
||||
if (result.stderr) {
|
||||
return result;
|
||||
}
|
||||
else if (result.stdout) {
|
||||
const annotationsSet = JSON.parse(result.stdout).metadata.annotations;
|
||||
if (annotationsSet && annotationsSet.runUri) {
|
||||
if (annotationsSet.runUri.indexOf(process.env['GITHUB_REPOSITORY']) == -1) {
|
||||
core.debug(`Skipping 'annotate namespace' as namespace annotated by other workflow`);
|
||||
return { code: 0, stdout: '' };
|
||||
}
|
||||
}
|
||||
return kubectl.annotate('namespace', namespaceName, constants_1.workflowAnnotations, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.annotateNamespace = annotateNamespace;
|
||||
function sleep(timeout) {
|
||||
return new Promise(resolve => setTimeout(resolve, timeout));
|
||||
}
|
||||
exports.sleep = sleep;
|
||||
function getRandomInt(max) {
|
||||
return Math.floor(Math.random() * Math.floor(max));
|
||||
}
|
||||
exports.getRandomInt = getRandomInt;
|
||||
function getCurrentTime() {
|
||||
return new Date().getTime();
|
||||
}
|
||||
exports.getCurrentTime = getCurrentTime;
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getNormalizedPath = exports.isHttpUrl = exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.normaliseWorkflowStrLabel = exports.getDeploymentConfig = exports.annotateChildPods = exports.getWorkflowFilePath = exports.getLastSuccessfulRunSha = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0;
|
||||
const os = require("os");
|
||||
const core = require("@actions/core");
|
||||
const githubClient_1 = require("../githubClient");
|
||||
const httpClient_1 = require("./httpClient");
|
||||
const inputParams = require("../input-parameters");
|
||||
const docker_object_model_1 = require("../docker-object-model");
|
||||
const io = require("@actions/io");
|
||||
function getExecutableExtension() {
|
||||
if (os.type().match(/^Win/)) {
|
||||
return '.exe';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
exports.getExecutableExtension = getExecutableExtension;
|
||||
function isEqual(str1, str2, ignoreCase) {
|
||||
if (str1 == null && str2 == null) {
|
||||
return true;
|
||||
}
|
||||
if (str1 == null || str2 == null) {
|
||||
return false;
|
||||
}
|
||||
if (ignoreCase) {
|
||||
return str1.toUpperCase() === str2.toUpperCase();
|
||||
}
|
||||
else {
|
||||
return str1 === str2;
|
||||
}
|
||||
}
|
||||
exports.isEqual = isEqual;
|
||||
function checkForErrors(execResults, warnIfError) {
|
||||
if (execResults.length !== 0) {
|
||||
let stderr = '';
|
||||
execResults.forEach(result => {
|
||||
if (result && result.stderr) {
|
||||
if (result.code !== 0) {
|
||||
stderr += result.stderr + '\n';
|
||||
}
|
||||
else {
|
||||
core.warning(result.stderr);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (stderr.length > 0) {
|
||||
if (warnIfError) {
|
||||
core.warning(stderr.trim());
|
||||
}
|
||||
else {
|
||||
throw new Error(stderr.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.checkForErrors = checkForErrors;
|
||||
function getLastSuccessfulRunSha(kubectl, namespaceName, annotationKey) {
|
||||
try {
|
||||
const result = kubectl.getResource('namespace', namespaceName);
|
||||
if (result) {
|
||||
if (result.stderr) {
|
||||
core.warning(`${result.stderr}`);
|
||||
return process.env.GITHUB_SHA;
|
||||
}
|
||||
else if (result.stdout) {
|
||||
const annotationsSet = JSON.parse(result.stdout).metadata.annotations;
|
||||
if (annotationsSet && annotationsSet[annotationKey]) {
|
||||
return JSON.parse(annotationsSet[annotationKey].replace(/'/g, '"')).commit;
|
||||
}
|
||||
else {
|
||||
return 'NA';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ex) {
|
||||
core.warning(`Failed to get commits from cluster. ${JSON.stringify(ex)}`);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
exports.getLastSuccessfulRunSha = getLastSuccessfulRunSha;
|
||||
function getWorkflowFilePath(githubToken) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let workflowFilePath = process.env.GITHUB_WORKFLOW;
|
||||
if (!workflowFilePath.startsWith('.github/workflows/')) {
|
||||
const githubClient = new githubClient_1.GitHubClient(process.env.GITHUB_REPOSITORY, githubToken);
|
||||
const response = yield githubClient.getWorkflows();
|
||||
if (response) {
|
||||
if (response.statusCode == httpClient_1.StatusCodes.OK
|
||||
&& response.body
|
||||
&& response.body.total_count) {
|
||||
if (response.body.total_count > 0) {
|
||||
for (let workflow of response.body.workflows) {
|
||||
if (process.env.GITHUB_WORKFLOW === workflow.name) {
|
||||
workflowFilePath = workflow.path;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (response.statusCode != httpClient_1.StatusCodes.OK) {
|
||||
core.debug(`An error occured while getting list of workflows on the repo. Statuscode: ${response.statusCode}, StatusMessage: ${response.statusMessage}`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
core.warning(`Failed to get response from workflow list API`);
|
||||
}
|
||||
}
|
||||
return Promise.resolve(workflowFilePath);
|
||||
});
|
||||
}
|
||||
exports.getWorkflowFilePath = getWorkflowFilePath;
|
||||
function annotateChildPods(kubectl, resourceType, resourceName, annotationKeyValStr, allPods) {
|
||||
const commandExecutionResults = [];
|
||||
let owner = resourceName;
|
||||
if (resourceType.toLowerCase().indexOf('deployment') > -1) {
|
||||
owner = kubectl.getNewReplicaSet(resourceName);
|
||||
}
|
||||
if (allPods && allPods.items && allPods.items.length > 0) {
|
||||
allPods.items.forEach((pod) => {
|
||||
const owners = pod.metadata.ownerReferences;
|
||||
if (owners) {
|
||||
for (let ownerRef of owners) {
|
||||
if (ownerRef.name === owner) {
|
||||
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, annotationKeyValStr));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return commandExecutionResults;
|
||||
}
|
||||
exports.annotateChildPods = annotateChildPods;
|
||||
function getDeploymentConfig() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let helmChartPaths = (process.env.HELM_CHART_PATHS && process.env.HELM_CHART_PATHS.split(';').filter(path => path != "")) || [];
|
||||
helmChartPaths = helmChartPaths.map(helmchart => getNormalizedPath(helmchart.trim()));
|
||||
let inputManifestFiles = inputParams.manifests || [];
|
||||
if (!helmChartPaths || helmChartPaths.length == 0) {
|
||||
inputManifestFiles = inputManifestFiles.map(manifestFile => getNormalizedPath(manifestFile));
|
||||
}
|
||||
const imageNames = inputParams.containers || [];
|
||||
let imageDockerfilePathMap = {};
|
||||
//Fetching from image label if available
|
||||
for (const image of imageNames) {
|
||||
try {
|
||||
imageDockerfilePathMap[image] = yield getDockerfilePath(image);
|
||||
}
|
||||
catch (ex) {
|
||||
core.warning(`Failed to get dockerfile path for image ${image.toString()} | ` + ex);
|
||||
}
|
||||
}
|
||||
const deploymentConfig = {
|
||||
manifestFilePaths: inputManifestFiles,
|
||||
helmChartFilePaths: helmChartPaths,
|
||||
dockerfilePaths: imageDockerfilePathMap
|
||||
};
|
||||
return Promise.resolve(deploymentConfig);
|
||||
});
|
||||
}
|
||||
exports.getDeploymentConfig = getDeploymentConfig;
|
||||
function normaliseWorkflowStrLabel(workflowName) {
|
||||
workflowName = workflowName.startsWith('.github/workflows/') ?
|
||||
workflowName.replace(".github/workflows/", "") : workflowName;
|
||||
return workflowName.replace(/ /g, "_");
|
||||
}
|
||||
exports.normaliseWorkflowStrLabel = normaliseWorkflowStrLabel;
|
||||
function sleep(timeout) {
|
||||
return new Promise(resolve => setTimeout(resolve, timeout));
|
||||
}
|
||||
exports.sleep = sleep;
|
||||
function getRandomInt(max) {
|
||||
return Math.floor(Math.random() * Math.floor(max));
|
||||
}
|
||||
exports.getRandomInt = getRandomInt;
|
||||
function getCurrentTime() {
|
||||
return new Date().getTime();
|
||||
}
|
||||
exports.getCurrentTime = getCurrentTime;
|
||||
function checkDockerPath() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let dockerPath = yield io.which('docker', false);
|
||||
if (!dockerPath) {
|
||||
throw new Error('Docker is not installed.');
|
||||
}
|
||||
});
|
||||
}
|
||||
function getDockerfilePath(image) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let imageConfig, imageInspectResult;
|
||||
var dockerExec = new docker_object_model_1.DockerExec('docker');
|
||||
yield checkDockerPath();
|
||||
dockerExec.pull(image, [], true);
|
||||
imageInspectResult = dockerExec.inspect(image, [], true);
|
||||
imageConfig = JSON.parse(imageInspectResult)[0];
|
||||
const DOCKERFILE_PATH_LABEL_KEY = 'dockerfile-path';
|
||||
let pathValue = '';
|
||||
if (imageConfig) {
|
||||
if ((imageConfig.Config) && (imageConfig.Config.Labels) && (imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY])) {
|
||||
const pathLabel = imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY];
|
||||
pathValue = getNormalizedPath(pathLabel);
|
||||
}
|
||||
}
|
||||
return Promise.resolve(pathValue);
|
||||
});
|
||||
}
|
||||
function isHttpUrl(url) {
|
||||
const HTTP_REGEX = /^https?:\/\/.*$/;
|
||||
return HTTP_REGEX.test(url);
|
||||
}
|
||||
exports.isHttpUrl = isHttpUrl;
|
||||
function getNormalizedPath(pathValue) {
|
||||
if (!isHttpUrl(pathValue)) { //if it is not an http url then convert to link from current repo and commit
|
||||
return `https://github.com/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${pathValue}`;
|
||||
}
|
||||
return pathValue;
|
||||
}
|
||||
exports.getNormalizedPath = getNormalizedPath;
|
||||
|
||||
+5925
File diff suppressed because it is too large
Load Diff
+9
@@ -0,0 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright 2019 GitHub
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
# `@actions/core`
|
||||
|
||||
> Core functions for setting results, logging, registering secrets and exporting variables across actions
|
||||
|
||||
## Usage
|
||||
|
||||
### Import the package
|
||||
|
||||
```js
|
||||
// javascript
|
||||
const core = require('@actions/core');
|
||||
|
||||
// typescript
|
||||
import * as core from '@actions/core';
|
||||
```
|
||||
|
||||
#### Inputs/Outputs
|
||||
|
||||
Action inputs can be read with `getInput` which returns a `string` or `getBooleanInput` which parses a boolean based on the [yaml 1.2 specification](https://yaml.org/spec/1.2/spec.html#id2804923). If `required` set to be false, the input should have a default value in `action.yml`.
|
||||
|
||||
Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled.
|
||||
|
||||
```js
|
||||
const myInput = core.getInput('inputName', { required: true });
|
||||
const myBooleanInput = core.getBooleanInput('booleanInputName', { required: true });
|
||||
const myMultilineInput = core.getMultilineInput('multilineInputName', { required: true });
|
||||
core.setOutput('outputKey', 'outputVal');
|
||||
```
|
||||
|
||||
#### Exporting variables
|
||||
|
||||
Since each step runs in a separate process, you can use `exportVariable` to add it to this step and future steps environment blocks.
|
||||
|
||||
```js
|
||||
core.exportVariable('envVar', 'Val');
|
||||
```
|
||||
|
||||
#### Setting a secret
|
||||
|
||||
Setting a secret registers the secret with the runner to ensure it is masked in logs.
|
||||
|
||||
```js
|
||||
core.setSecret('myPassword');
|
||||
```
|
||||
|
||||
#### PATH Manipulation
|
||||
|
||||
To make a tool's path available in the path for the remainder of the job (without altering the machine or containers state), use `addPath`. The runner will prepend the path given to the jobs PATH.
|
||||
|
||||
```js
|
||||
core.addPath('/path/to/mytool');
|
||||
```
|
||||
|
||||
#### Exit codes
|
||||
|
||||
You should use this library to set the failing exit code for your action. If status is not set and the script runs to completion, that will lead to a success.
|
||||
|
||||
```js
|
||||
const core = require('@actions/core');
|
||||
|
||||
try {
|
||||
// Do stuff
|
||||
}
|
||||
catch (err) {
|
||||
// setFailed logs the message and sets a failing exit code
|
||||
core.setFailed(`Action failed with error ${err}`);
|
||||
}
|
||||
```
|
||||
|
||||
Note that `setNeutral` is not yet implemented in actions V2 but equivalent functionality is being planned.
|
||||
|
||||
#### Logging
|
||||
|
||||
Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the [Step Debug Logs](../../docs/action-debugging.md#step-debug-logs).
|
||||
|
||||
```js
|
||||
const core = require('@actions/core');
|
||||
|
||||
const myInput = core.getInput('input');
|
||||
try {
|
||||
core.debug('Inside try block');
|
||||
|
||||
if (!myInput) {
|
||||
core.warning('myInput was not set');
|
||||
}
|
||||
|
||||
if (core.isDebug()) {
|
||||
// curl -v https://github.com
|
||||
} else {
|
||||
// curl https://github.com
|
||||
}
|
||||
|
||||
// Do stuff
|
||||
core.info('Output to the actions build log')
|
||||
}
|
||||
catch (err) {
|
||||
core.error(`Error ${err}, action may still succeed though`);
|
||||
}
|
||||
```
|
||||
|
||||
This library can also wrap chunks of output in foldable groups.
|
||||
|
||||
```js
|
||||
const core = require('@actions/core')
|
||||
|
||||
// Manually wrap output
|
||||
core.startGroup('Do some function')
|
||||
doSomeFunction()
|
||||
core.endGroup()
|
||||
|
||||
// Wrap an asynchronous function call
|
||||
const result = await core.group('Do something async', async () => {
|
||||
const response = await doSomeHTTPRequest()
|
||||
return response
|
||||
})
|
||||
```
|
||||
|
||||
#### Styling output
|
||||
|
||||
Colored output is supported in the Action logs via standard [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). 3/4 bit, 8 bit and 24 bit colors are all supported.
|
||||
|
||||
Foreground colors:
|
||||
|
||||
```js
|
||||
// 3/4 bit
|
||||
core.info('\u001b[35mThis foreground will be magenta')
|
||||
|
||||
// 8 bit
|
||||
core.info('\u001b[38;5;6mThis foreground will be cyan')
|
||||
|
||||
// 24 bit
|
||||
core.info('\u001b[38;2;255;0;0mThis foreground will be bright red')
|
||||
```
|
||||
|
||||
Background colors:
|
||||
|
||||
```js
|
||||
// 3/4 bit
|
||||
core.info('\u001b[43mThis background will be yellow');
|
||||
|
||||
// 8 bit
|
||||
core.info('\u001b[48;5;6mThis background will be cyan')
|
||||
|
||||
// 24 bit
|
||||
core.info('\u001b[48;2;255;0;0mThis background will be bright red')
|
||||
```
|
||||
|
||||
Special styles:
|
||||
|
||||
```js
|
||||
core.info('\u001b[1mBold text')
|
||||
core.info('\u001b[3mItalic text')
|
||||
core.info('\u001b[4mUnderlined text')
|
||||
```
|
||||
|
||||
ANSI escape codes can be combined with one another:
|
||||
|
||||
```js
|
||||
core.info('\u001b[31;46mRed foreground with a cyan background and \u001b[1mbold text at the end');
|
||||
```
|
||||
|
||||
> Note: Escape codes reset at the start of each line
|
||||
|
||||
```js
|
||||
core.info('\u001b[35mThis foreground will be magenta')
|
||||
core.info('This foreground will reset to the default')
|
||||
```
|
||||
|
||||
Manually typing escape codes can be a little difficult, but you can use third party modules such as [ansi-styles](https://github.com/chalk/ansi-styles).
|
||||
|
||||
```js
|
||||
const style = require('ansi-styles');
|
||||
core.info(style.color.ansi16m.hex('#abcdef') + 'Hello world!')
|
||||
```
|
||||
|
||||
#### Action state
|
||||
|
||||
You can use this library to save state and get state for sharing information between a given wrapper action:
|
||||
|
||||
**action.yml**:
|
||||
|
||||
```yaml
|
||||
name: 'Wrapper action sample'
|
||||
inputs:
|
||||
name:
|
||||
default: 'GitHub'
|
||||
runs:
|
||||
using: 'node12'
|
||||
main: 'main.js'
|
||||
post: 'cleanup.js'
|
||||
```
|
||||
|
||||
In action's `main.js`:
|
||||
|
||||
```js
|
||||
const core = require('@actions/core');
|
||||
|
||||
core.saveState("pidToKill", 12345);
|
||||
```
|
||||
|
||||
In action's `cleanup.js`:
|
||||
|
||||
```js
|
||||
const core = require('@actions/core');
|
||||
|
||||
var pid = core.getState("pidToKill");
|
||||
|
||||
process.kill(pid);
|
||||
```
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
interface CommandProperties {
|
||||
[key: string]: any;
|
||||
}
|
||||
/**
|
||||
* Commands
|
||||
*
|
||||
* Command Format:
|
||||
* ::name key=value,key=value::message
|
||||
*
|
||||
* Examples:
|
||||
* ::warning::This is the message
|
||||
* ::set-env name=MY_VAR::some value
|
||||
*/
|
||||
export declare function issueCommand(command: string, properties: CommandProperties, message: any): void;
|
||||
export declare function issue(name: string, message?: string): void;
|
||||
export {};
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.issue = exports.issueCommand = void 0;
|
||||
const os = __importStar(require("os"));
|
||||
const utils_1 = require("./utils");
|
||||
/**
|
||||
* Commands
|
||||
*
|
||||
* Command Format:
|
||||
* ::name key=value,key=value::message
|
||||
*
|
||||
* Examples:
|
||||
* ::warning::This is the message
|
||||
* ::set-env name=MY_VAR::some value
|
||||
*/
|
||||
function issueCommand(command, properties, message) {
|
||||
const cmd = new Command(command, properties, message);
|
||||
process.stdout.write(cmd.toString() + os.EOL);
|
||||
}
|
||||
exports.issueCommand = issueCommand;
|
||||
function issue(name, message = '') {
|
||||
issueCommand(name, {}, message);
|
||||
}
|
||||
exports.issue = issue;
|
||||
const CMD_STRING = '::';
|
||||
class Command {
|
||||
constructor(command, properties, message) {
|
||||
if (!command) {
|
||||
command = 'missing.command';
|
||||
}
|
||||
this.command = command;
|
||||
this.properties = properties;
|
||||
this.message = message;
|
||||
}
|
||||
toString() {
|
||||
let cmdStr = CMD_STRING + this.command;
|
||||
if (this.properties && Object.keys(this.properties).length > 0) {
|
||||
cmdStr += ' ';
|
||||
let first = true;
|
||||
for (const key in this.properties) {
|
||||
if (this.properties.hasOwnProperty(key)) {
|
||||
const val = this.properties[key];
|
||||
if (val) {
|
||||
if (first) {
|
||||
first = false;
|
||||
}
|
||||
else {
|
||||
cmdStr += ',';
|
||||
}
|
||||
cmdStr += `${key}=${escapeProperty(val)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
|
||||
return cmdStr;
|
||||
}
|
||||
}
|
||||
function escapeData(s) {
|
||||
return utils_1.toCommandValue(s)
|
||||
.replace(/%/g, '%25')
|
||||
.replace(/\r/g, '%0D')
|
||||
.replace(/\n/g, '%0A');
|
||||
}
|
||||
function escapeProperty(s) {
|
||||
return utils_1.toCommandValue(s)
|
||||
.replace(/%/g, '%25')
|
||||
.replace(/\r/g, '%0D')
|
||||
.replace(/\n/g, '%0A')
|
||||
.replace(/:/g, '%3A')
|
||||
.replace(/,/g, '%2C');
|
||||
}
|
||||
//# sourceMappingURL=command.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAwB;AACxB,mCAAsC;AAWtC;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAY;IAEZ,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,OAAO,GAAG,EAAE;IAC9C,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAM;IACxB,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAM;IAC5B,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Interface for getInput options
|
||||
*/
|
||||
export interface InputOptions {
|
||||
/** Optional. Whether the input is required. If required and not present, will throw. Defaults to false */
|
||||
required?: boolean;
|
||||
/** Optional. Whether leading/trailing whitespace will be trimmed for the input. Defaults to true */
|
||||
trimWhitespace?: boolean;
|
||||
}
|
||||
/**
|
||||
* The code to exit an action
|
||||
*/
|
||||
export declare enum ExitCode {
|
||||
/**
|
||||
* A code indicating that the action was successful
|
||||
*/
|
||||
Success = 0,
|
||||
/**
|
||||
* A code indicating that the action was a failure
|
||||
*/
|
||||
Failure = 1
|
||||
}
|
||||
/**
|
||||
* Sets env variable for this action and future actions in the job
|
||||
* @param name the name of the variable to set
|
||||
* @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
|
||||
*/
|
||||
export declare function exportVariable(name: string, val: any): void;
|
||||
/**
|
||||
* Registers a secret which will get masked from logs
|
||||
* @param secret value of the secret
|
||||
*/
|
||||
export declare function setSecret(secret: string): void;
|
||||
/**
|
||||
* Prepends inputPath to the PATH (for this action and future actions)
|
||||
* @param inputPath
|
||||
*/
|
||||
export declare function addPath(inputPath: string): void;
|
||||
/**
|
||||
* Gets the value of an input.
|
||||
* Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
|
||||
* Returns an empty string if the value is not defined.
|
||||
*
|
||||
* @param name name of the input to get
|
||||
* @param options optional. See InputOptions.
|
||||
* @returns string
|
||||
*/
|
||||
export declare function getInput(name: string, options?: InputOptions): string;
|
||||
/**
|
||||
* Gets the values of an multiline input. Each value is also trimmed.
|
||||
*
|
||||
* @param name name of the input to get
|
||||
* @param options optional. See InputOptions.
|
||||
* @returns string[]
|
||||
*
|
||||
*/
|
||||
export declare function getMultilineInput(name: string, options?: InputOptions): string[];
|
||||
/**
|
||||
* Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
|
||||
* Support boolean input list: `true | True | TRUE | false | False | FALSE` .
|
||||
* The return value is also in boolean type.
|
||||
* ref: https://yaml.org/spec/1.2/spec.html#id2804923
|
||||
*
|
||||
* @param name name of the input to get
|
||||
* @param options optional. See InputOptions.
|
||||
* @returns boolean
|
||||
*/
|
||||
export declare function getBooleanInput(name: string, options?: InputOptions): boolean;
|
||||
/**
|
||||
* Sets the value of an output.
|
||||
*
|
||||
* @param name name of the output to set
|
||||
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
|
||||
*/
|
||||
export declare function setOutput(name: string, value: any): void;
|
||||
/**
|
||||
* Enables or disables the echoing of commands into stdout for the rest of the step.
|
||||
* Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
|
||||
*
|
||||
*/
|
||||
export declare function setCommandEcho(enabled: boolean): void;
|
||||
/**
|
||||
* Sets the action status to failed.
|
||||
* When the action exits it will be with an exit code of 1
|
||||
* @param message add error issue message
|
||||
*/
|
||||
export declare function setFailed(message: string | Error): void;
|
||||
/**
|
||||
* Gets whether Actions Step Debug is on or not
|
||||
*/
|
||||
export declare function isDebug(): boolean;
|
||||
/**
|
||||
* Writes debug message to user log
|
||||
* @param message debug message
|
||||
*/
|
||||
export declare function debug(message: string): void;
|
||||
/**
|
||||
* Adds an error issue
|
||||
* @param message error issue message. Errors will be converted to string via toString()
|
||||
*/
|
||||
export declare function error(message: string | Error): void;
|
||||
/**
|
||||
* Adds an warning issue
|
||||
* @param message warning issue message. Errors will be converted to string via toString()
|
||||
*/
|
||||
export declare function warning(message: string | Error): void;
|
||||
/**
|
||||
* Writes info to log with console.log.
|
||||
* @param message info message
|
||||
*/
|
||||
export declare function info(message: string): void;
|
||||
/**
|
||||
* Begin an output group.
|
||||
*
|
||||
* Output until the next `groupEnd` will be foldable in this group
|
||||
*
|
||||
* @param name The name of the output group
|
||||
*/
|
||||
export declare function startGroup(name: string): void;
|
||||
/**
|
||||
* End an output group.
|
||||
*/
|
||||
export declare function endGroup(): void;
|
||||
/**
|
||||
* Wrap an asynchronous function call in a group.
|
||||
*
|
||||
* Returns the same type as the function itself.
|
||||
*
|
||||
* @param name The name of the group
|
||||
* @param fn The function to wrap in the group
|
||||
*/
|
||||
export declare function group<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
||||
/**
|
||||
* Saves state for current action, the state can only be retrieved by this action's post job execution.
|
||||
*
|
||||
* @param name name of the state to store
|
||||
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
|
||||
*/
|
||||
export declare function saveState(name: string, value: any): void;
|
||||
/**
|
||||
* Gets the value of an state set by this action's main execution.
|
||||
*
|
||||
* @param name name of the state to get
|
||||
* @returns string
|
||||
*/
|
||||
export declare function getState(name: string): string;
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
|
||||
const command_1 = require("./command");
|
||||
const file_command_1 = require("./file-command");
|
||||
const utils_1 = require("./utils");
|
||||
const os = __importStar(require("os"));
|
||||
const path = __importStar(require("path"));
|
||||
/**
|
||||
* The code to exit an action
|
||||
*/
|
||||
var ExitCode;
|
||||
(function (ExitCode) {
|
||||
/**
|
||||
* A code indicating that the action was successful
|
||||
*/
|
||||
ExitCode[ExitCode["Success"] = 0] = "Success";
|
||||
/**
|
||||
* A code indicating that the action was a failure
|
||||
*/
|
||||
ExitCode[ExitCode["Failure"] = 1] = "Failure";
|
||||
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
|
||||
//-----------------------------------------------------------------------
|
||||
// Variables
|
||||
//-----------------------------------------------------------------------
|
||||
/**
|
||||
* Sets env variable for this action and future actions in the job
|
||||
* @param name the name of the variable to set
|
||||
* @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function exportVariable(name, val) {
|
||||
const convertedVal = utils_1.toCommandValue(val);
|
||||
process.env[name] = convertedVal;
|
||||
const filePath = process.env['GITHUB_ENV'] || '';
|
||||
if (filePath) {
|
||||
const delimiter = '_GitHubActionsFileCommandDelimeter_';
|
||||
const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;
|
||||
file_command_1.issueCommand('ENV', commandValue);
|
||||
}
|
||||
else {
|
||||
command_1.issueCommand('set-env', { name }, convertedVal);
|
||||
}
|
||||
}
|
||||
exports.exportVariable = exportVariable;
|
||||
/**
|
||||
* Registers a secret which will get masked from logs
|
||||
* @param secret value of the secret
|
||||
*/
|
||||
function setSecret(secret) {
|
||||
command_1.issueCommand('add-mask', {}, secret);
|
||||
}
|
||||
exports.setSecret = setSecret;
|
||||
/**
|
||||
* Prepends inputPath to the PATH (for this action and future actions)
|
||||
* @param inputPath
|
||||
*/
|
||||
function addPath(inputPath) {
|
||||
const filePath = process.env['GITHUB_PATH'] || '';
|
||||
if (filePath) {
|
||||
file_command_1.issueCommand('PATH', inputPath);
|
||||
}
|
||||
else {
|
||||
command_1.issueCommand('add-path', {}, inputPath);
|
||||
}
|
||||
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
|
||||
}
|
||||
exports.addPath = addPath;
|
||||
/**
|
||||
* Gets the value of an input.
|
||||
* Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
|
||||
* Returns an empty string if the value is not defined.
|
||||
*
|
||||
* @param name name of the input to get
|
||||
* @param options optional. See InputOptions.
|
||||
* @returns string
|
||||
*/
|
||||
function getInput(name, options) {
|
||||
const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
|
||||
if (options && options.required && !val) {
|
||||
throw new Error(`Input required and not supplied: ${name}`);
|
||||
}
|
||||
if (options && options.trimWhitespace === false) {
|
||||
return val;
|
||||
}
|
||||
return val.trim();
|
||||
}
|
||||
exports.getInput = getInput;
|
||||
/**
|
||||
* Gets the values of an multiline input. Each value is also trimmed.
|
||||
*
|
||||
* @param name name of the input to get
|
||||
* @param options optional. See InputOptions.
|
||||
* @returns string[]
|
||||
*
|
||||
*/
|
||||
function getMultilineInput(name, options) {
|
||||
const inputs = getInput(name, options)
|
||||
.split('\n')
|
||||
.filter(x => x !== '');
|
||||
return inputs;
|
||||
}
|
||||
exports.getMultilineInput = getMultilineInput;
|
||||
/**
|
||||
* Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
|
||||
* Support boolean input list: `true | True | TRUE | false | False | FALSE` .
|
||||
* The return value is also in boolean type.
|
||||
* ref: https://yaml.org/spec/1.2/spec.html#id2804923
|
||||
*
|
||||
* @param name name of the input to get
|
||||
* @param options optional. See InputOptions.
|
||||
* @returns boolean
|
||||
*/
|
||||
function getBooleanInput(name, options) {
|
||||
const trueValue = ['true', 'True', 'TRUE'];
|
||||
const falseValue = ['false', 'False', 'FALSE'];
|
||||
const val = getInput(name, options);
|
||||
if (trueValue.includes(val))
|
||||
return true;
|
||||
if (falseValue.includes(val))
|
||||
return false;
|
||||
throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
|
||||
`Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
|
||||
}
|
||||
exports.getBooleanInput = getBooleanInput;
|
||||
/**
|
||||
* Sets the value of an output.
|
||||
*
|
||||
* @param name name of the output to set
|
||||
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function setOutput(name, value) {
|
||||
process.stdout.write(os.EOL);
|
||||
command_1.issueCommand('set-output', { name }, value);
|
||||
}
|
||||
exports.setOutput = setOutput;
|
||||
/**
|
||||
* Enables or disables the echoing of commands into stdout for the rest of the step.
|
||||
* Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
|
||||
*
|
||||
*/
|
||||
function setCommandEcho(enabled) {
|
||||
command_1.issue('echo', enabled ? 'on' : 'off');
|
||||
}
|
||||
exports.setCommandEcho = setCommandEcho;
|
||||
//-----------------------------------------------------------------------
|
||||
// Results
|
||||
//-----------------------------------------------------------------------
|
||||
/**
|
||||
* Sets the action status to failed.
|
||||
* When the action exits it will be with an exit code of 1
|
||||
* @param message add error issue message
|
||||
*/
|
||||
function setFailed(message) {
|
||||
process.exitCode = ExitCode.Failure;
|
||||
error(message);
|
||||
}
|
||||
exports.setFailed = setFailed;
|
||||
//-----------------------------------------------------------------------
|
||||
// Logging Commands
|
||||
//-----------------------------------------------------------------------
|
||||
/**
|
||||
* Gets whether Actions Step Debug is on or not
|
||||
*/
|
||||
function isDebug() {
|
||||
return process.env['RUNNER_DEBUG'] === '1';
|
||||
}
|
||||
exports.isDebug = isDebug;
|
||||
/**
|
||||
* Writes debug message to user log
|
||||
* @param message debug message
|
||||
*/
|
||||
function debug(message) {
|
||||
command_1.issueCommand('debug', {}, message);
|
||||
}
|
||||
exports.debug = debug;
|
||||
/**
|
||||
* Adds an error issue
|
||||
* @param message error issue message. Errors will be converted to string via toString()
|
||||
*/
|
||||
function error(message) {
|
||||
command_1.issue('error', message instanceof Error ? message.toString() : message);
|
||||
}
|
||||
exports.error = error;
|
||||
/**
|
||||
* Adds an warning issue
|
||||
* @param message warning issue message. Errors will be converted to string via toString()
|
||||
*/
|
||||
function warning(message) {
|
||||
command_1.issue('warning', message instanceof Error ? message.toString() : message);
|
||||
}
|
||||
exports.warning = warning;
|
||||
/**
|
||||
* Writes info to log with console.log.
|
||||
* @param message info message
|
||||
*/
|
||||
function info(message) {
|
||||
process.stdout.write(message + os.EOL);
|
||||
}
|
||||
exports.info = info;
|
||||
/**
|
||||
* Begin an output group.
|
||||
*
|
||||
* Output until the next `groupEnd` will be foldable in this group
|
||||
*
|
||||
* @param name The name of the output group
|
||||
*/
|
||||
function startGroup(name) {
|
||||
command_1.issue('group', name);
|
||||
}
|
||||
exports.startGroup = startGroup;
|
||||
/**
|
||||
* End an output group.
|
||||
*/
|
||||
function endGroup() {
|
||||
command_1.issue('endgroup');
|
||||
}
|
||||
exports.endGroup = endGroup;
|
||||
/**
|
||||
* Wrap an asynchronous function call in a group.
|
||||
*
|
||||
* Returns the same type as the function itself.
|
||||
*
|
||||
* @param name The name of the group
|
||||
* @param fn The function to wrap in the group
|
||||
*/
|
||||
function group(name, fn) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
startGroup(name);
|
||||
let result;
|
||||
try {
|
||||
result = yield fn();
|
||||
}
|
||||
finally {
|
||||
endGroup();
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
exports.group = group;
|
||||
//-----------------------------------------------------------------------
|
||||
// Wrapper action state
|
||||
//-----------------------------------------------------------------------
|
||||
/**
|
||||
* Saves state for current action, the state can only be retrieved by this action's post job execution.
|
||||
*
|
||||
* @param name name of the state to store
|
||||
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function saveState(name, value) {
|
||||
command_1.issueCommand('save-state', { name }, value);
|
||||
}
|
||||
exports.saveState = saveState;
|
||||
/**
|
||||
* Gets the value of an state set by this action's main execution.
|
||||
*
|
||||
* @param name name of the state to get
|
||||
* @returns string
|
||||
*/
|
||||
function getState(name) {
|
||||
return process.env[`STATE_${name}`] || '';
|
||||
}
|
||||
exports.getState = getState;
|
||||
//# sourceMappingURL=core.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAA6C;AAC7C,iDAA+D;AAC/D,mCAAsC;AAEtC,uCAAwB;AACxB,2CAA4B;AAa5B;;GAEG;AACH,IAAY,QAUX;AAVD,WAAY,QAAQ;IAClB;;OAEG;IACH,6CAAW,CAAA;IAEX;;OAEG;IACH,6CAAW,CAAA;AACb,CAAC,EAVW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAUnB;AAED,yEAAyE;AACzE,YAAY;AACZ,yEAAyE;AAEzE;;;;GAIG;AACH,8DAA8D;AAC9D,SAAgB,cAAc,CAAC,IAAY,EAAE,GAAQ;IACnD,MAAM,YAAY,GAAG,sBAAc,CAAC,GAAG,CAAC,CAAA;IACxC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,YAAY,CAAA;IAEhC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,EAAE,CAAA;IAChD,IAAI,QAAQ,EAAE;QACZ,MAAM,SAAS,GAAG,qCAAqC,CAAA;QACvD,MAAM,YAAY,GAAG,GAAG,IAAI,KAAK,SAAS,GAAG,EAAE,CAAC,GAAG,GAAG,YAAY,GAAG,EAAE,CAAC,GAAG,GAAG,SAAS,EAAE,CAAA;QACzF,2BAAgB,CAAC,KAAK,EAAE,YAAY,CAAC,CAAA;KACtC;SAAM;QACL,sBAAY,CAAC,SAAS,EAAE,EAAC,IAAI,EAAC,EAAE,YAAY,CAAC,CAAA;KAC9C;AACH,CAAC;AAZD,wCAYC;AAED;;;GAGG;AACH,SAAgB,SAAS,CAAC,MAAc;IACtC,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,MAAM,CAAC,CAAA;AACtC,CAAC;AAFD,8BAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,SAAiB;IACvC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE,CAAA;IACjD,IAAI,QAAQ,EAAE;QACZ,2BAAgB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;KACpC;SAAM;QACL,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,SAAS,CAAC,CAAA;KACxC;IACD,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAA;AAC7E,CAAC;AARD,0BAQC;AAED;;;;;;;;GAQG;AACH,SAAgB,QAAQ,CAAC,IAAY,EAAE,OAAsB;IAC3D,MAAM,GAAG,GACP,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,IAAI,EAAE,CAAA;IACrE,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,IAAI,CAAC,GAAG,EAAE;QACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAA;KAC5D;IAED,IAAI,OAAO,IAAI,OAAO,CAAC,cAAc,KAAK,KAAK,EAAE;QAC/C,OAAO,GAAG,CAAA;KACX;IAED,OAAO,GAAG,CAAC,IAAI,EAAE,CAAA;AACnB,CAAC;AAZD,4BAYC;AAED;;;;;;;GAOG;AACH,SAAgB,iBAAiB,CAC/B,IAAY,EACZ,OAAsB;IAEtB,MAAM,MAAM,GAAa,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;SAC7C,KAAK,CAAC,IAAI,CAAC;SACX,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;IAExB,OAAO,MAAM,CAAA;AACf,CAAC;AATD,8CASC;AAED;;;;;;;;;GASG;AACH,SAAgB,eAAe,CAAC,IAAY,EAAE,OAAsB;IAClE,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;IAC1C,MAAM,UAAU,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;IAC9C,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACnC,IAAI,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAA;IACxC,IAAI,UAAU,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAA;IAC1C,MAAM,IAAI,SAAS,CACjB,6DAA6D,IAAI,IAAI;QACnE,4EAA4E,CAC/E,CAAA;AACH,CAAC;AAVD,0CAUC;AAED;;;;;GAKG;AACH,8DAA8D;AAC9D,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAU;IAChD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,CAAA;IAC5B,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAHD,8BAGC;AAED;;;;GAIG;AACH,SAAgB,cAAc,CAAC,OAAgB;IAC7C,eAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAA;AACvC,CAAC;AAFD,wCAEC;AAED,yEAAyE;AACzE,UAAU;AACV,yEAAyE;AAEzE;;;;GAIG;AACH,SAAgB,SAAS,CAAC,OAAuB;IAC/C,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAA;IAEnC,KAAK,CAAC,OAAO,CAAC,CAAA;AAChB,CAAC;AAJD,8BAIC;AAED,yEAAyE;AACzE,mBAAmB;AACnB,yEAAyE;AAEzE;;GAEG;AACH,SAAgB,OAAO;IACrB,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,KAAK,GAAG,CAAA;AAC5C,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAe;IACnC,sBAAY,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAuB;IAC3C,eAAK,CAAC,OAAO,EAAE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;AACzE,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,OAAuB;IAC7C,eAAK,CAAC,SAAS,EAAE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;AAC3E,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,IAAI,CAAC,OAAe;IAClC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AACxC,CAAC;AAFD,oBAEC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,IAAY;IACrC,eAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAFD,gCAEC;AAED;;GAEG;AACH,SAAgB,QAAQ;IACtB,eAAK,CAAC,UAAU,CAAC,CAAA;AACnB,CAAC;AAFD,4BAEC;AAED;;;;;;;GAOG;AACH,SAAsB,KAAK,CAAI,IAAY,EAAE,EAAoB;;QAC/D,UAAU,CAAC,IAAI,CAAC,CAAA;QAEhB,IAAI,MAAS,CAAA;QAEb,IAAI;YACF,MAAM,GAAG,MAAM,EAAE,EAAE,CAAA;SACpB;gBAAS;YACR,QAAQ,EAAE,CAAA;SACX;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CAAA;AAZD,sBAYC;AAED,yEAAyE;AACzE,uBAAuB;AACvB,yEAAyE;AAEzE;;;;;GAKG;AACH,8DAA8D;AAC9D,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAU;IAChD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC,IAAI,EAAE,CAAA;AAC3C,CAAC;AAFD,4BAEC"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function issueCommand(command: string, message: any): void;
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
"use strict";
|
||||
// For internal use, subject to change.
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.issueCommand = void 0;
|
||||
// We use any as a valid input type
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
const fs = __importStar(require("fs"));
|
||||
const os = __importStar(require("os"));
|
||||
const utils_1 = require("./utils");
|
||||
function issueCommand(command, message) {
|
||||
const filePath = process.env[`GITHUB_${command}`];
|
||||
if (!filePath) {
|
||||
throw new Error(`Unable to find environment variable for file command ${command}`);
|
||||
}
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error(`Missing file at path: ${filePath}`);
|
||||
}
|
||||
fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {
|
||||
encoding: 'utf8'
|
||||
});
|
||||
}
|
||||
exports.issueCommand = issueCommand;
|
||||
//# sourceMappingURL=file-command.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"file-command.js","sourceRoot":"","sources":["../src/file-command.ts"],"names":[],"mappings":";AAAA,uCAAuC;;;;;;;;;;;;;;;;;;;;;;AAEvC,mCAAmC;AACnC,uDAAuD;AAEvD,uCAAwB;AACxB,uCAAwB;AACxB,mCAAsC;AAEtC,SAAgB,YAAY,CAAC,OAAe,EAAE,OAAY;IACxD,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,OAAO,EAAE,CAAC,CAAA;IACjD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CACb,wDAAwD,OAAO,EAAE,CAClE,CAAA;KACF;IACD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,yBAAyB,QAAQ,EAAE,CAAC,CAAA;KACrD;IAED,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE,GAAG,sBAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACjE,QAAQ,EAAE,MAAM;KACjB,CAAC,CAAA;AACJ,CAAC;AAdD,oCAcC"}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* Sanitizes an input into a string so it can be passed into issueCommand safely
|
||||
* @param input input to sanitize into a string
|
||||
*/
|
||||
export declare function toCommandValue(input: any): string;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
// We use any as a valid input type
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.toCommandValue = void 0;
|
||||
/**
|
||||
* Sanitizes an input into a string so it can be passed into issueCommand safely
|
||||
* @param input input to sanitize into a string
|
||||
*/
|
||||
function toCommandValue(input) {
|
||||
if (input === null || input === undefined) {
|
||||
return '';
|
||||
}
|
||||
else if (typeof input === 'string' || input instanceof String) {
|
||||
return input;
|
||||
}
|
||||
return JSON.stringify(input);
|
||||
}
|
||||
exports.toCommandValue = toCommandValue;
|
||||
//# sourceMappingURL=utils.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA,mCAAmC;AACnC,uDAAuD;;;AAEvD;;;GAGG;AACH,SAAgB,cAAc,CAAC,KAAU;IACvC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE;QACzC,OAAO,EAAE,CAAA;KACV;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,YAAY,MAAM,EAAE;QAC/D,OAAO,KAAe,CAAA;KACvB;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAC9B,CAAC;AAPD,wCAOC"}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@actions/core",
|
||||
"version": "1.4.0",
|
||||
"description": "Actions core lib",
|
||||
"keywords": [
|
||||
"github",
|
||||
"actions",
|
||||
"core"
|
||||
],
|
||||
"homepage": "https://github.com/actions/toolkit/tree/main/packages/core",
|
||||
"license": "MIT",
|
||||
"main": "lib/core.js",
|
||||
"types": "lib/core.d.ts",
|
||||
"directories": {
|
||||
"lib": "lib",
|
||||
"test": "__tests__"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"!.DS_Store"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/actions/toolkit.git",
|
||||
"directory": "packages/core"
|
||||
},
|
||||
"scripts": {
|
||||
"audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/actions/toolkit/issues"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^12.0.2"
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright 2019 GitHub
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
# `@actions/exec`
|
||||
|
||||
## Usage
|
||||
|
||||
#### Basic
|
||||
|
||||
You can use this package to execute tools in a cross platform way:
|
||||
|
||||
```js
|
||||
const exec = require('@actions/exec');
|
||||
|
||||
await exec.exec('node index.js');
|
||||
```
|
||||
|
||||
#### Args
|
||||
|
||||
You can also pass in arg arrays:
|
||||
|
||||
```js
|
||||
const exec = require('@actions/exec');
|
||||
|
||||
await exec.exec('node', ['index.js', 'foo=bar']);
|
||||
```
|
||||
|
||||
#### Output/options
|
||||
|
||||
Capture output or specify [other options](https://github.com/actions/toolkit/blob/d9347d4ab99fd507c0b9104b2cf79fb44fcc827d/packages/exec/src/interfaces.ts#L5):
|
||||
|
||||
```js
|
||||
const exec = require('@actions/exec');
|
||||
|
||||
let myOutput = '';
|
||||
let myError = '';
|
||||
|
||||
const options = {};
|
||||
options.listeners = {
|
||||
stdout: (data: Buffer) => {
|
||||
myOutput += data.toString();
|
||||
},
|
||||
stderr: (data: Buffer) => {
|
||||
myError += data.toString();
|
||||
}
|
||||
};
|
||||
options.cwd = './lib';
|
||||
|
||||
await exec.exec('node', ['index.js', 'foo=bar'], options);
|
||||
```
|
||||
|
||||
#### Exec tools not in the PATH
|
||||
|
||||
You can specify the full path for tools not in the PATH:
|
||||
|
||||
```js
|
||||
const exec = require('@actions/exec');
|
||||
|
||||
await exec.exec('"/path/to/my-tool"', ['arg1']);
|
||||
```
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import { ExecOptions, ExecOutput, ExecListeners } from './interfaces';
|
||||
export { ExecOptions, ExecOutput, ExecListeners };
|
||||
/**
|
||||
* Exec a command.
|
||||
* Output will be streamed to the live console.
|
||||
* Returns promise with return code
|
||||
*
|
||||
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
||||
* @param args optional arguments for tool. Escaping is handled by the lib.
|
||||
* @param options optional exec options. See ExecOptions
|
||||
* @returns Promise<number> exit code
|
||||
*/
|
||||
export declare function exec(commandLine: string, args?: string[], options?: ExecOptions): Promise<number>;
|
||||
/**
|
||||
* Exec a command and get the output.
|
||||
* Output will be streamed to the live console.
|
||||
* Returns promise with the exit code and collected stdout and stderr
|
||||
*
|
||||
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
||||
* @param args optional arguments for tool. Escaping is handled by the lib.
|
||||
* @param options optional exec options. See ExecOptions
|
||||
* @returns Promise<ExecOutput> exit code, stdout, and stderr
|
||||
*/
|
||||
export declare function getExecOutput(commandLine: string, args?: string[], options?: ExecOptions): Promise<ExecOutput>;
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getExecOutput = exports.exec = void 0;
|
||||
const string_decoder_1 = require("string_decoder");
|
||||
const tr = __importStar(require("./toolrunner"));
|
||||
/**
|
||||
* Exec a command.
|
||||
* Output will be streamed to the live console.
|
||||
* Returns promise with return code
|
||||
*
|
||||
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
||||
* @param args optional arguments for tool. Escaping is handled by the lib.
|
||||
* @param options optional exec options. See ExecOptions
|
||||
* @returns Promise<number> exit code
|
||||
*/
|
||||
function exec(commandLine, args, options) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const commandArgs = tr.argStringToArray(commandLine);
|
||||
if (commandArgs.length === 0) {
|
||||
throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
|
||||
}
|
||||
// Path to tool to execute should be first arg
|
||||
const toolPath = commandArgs[0];
|
||||
args = commandArgs.slice(1).concat(args || []);
|
||||
const runner = new tr.ToolRunner(toolPath, args, options);
|
||||
return runner.exec();
|
||||
});
|
||||
}
|
||||
exports.exec = exec;
|
||||
/**
|
||||
* Exec a command and get the output.
|
||||
* Output will be streamed to the live console.
|
||||
* Returns promise with the exit code and collected stdout and stderr
|
||||
*
|
||||
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
||||
* @param args optional arguments for tool. Escaping is handled by the lib.
|
||||
* @param options optional exec options. See ExecOptions
|
||||
* @returns Promise<ExecOutput> exit code, stdout, and stderr
|
||||
*/
|
||||
function getExecOutput(commandLine, args, options) {
|
||||
var _a, _b;
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
//Using string decoder covers the case where a mult-byte character is split
|
||||
const stdoutDecoder = new string_decoder_1.StringDecoder('utf8');
|
||||
const stderrDecoder = new string_decoder_1.StringDecoder('utf8');
|
||||
const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout;
|
||||
const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr;
|
||||
const stdErrListener = (data) => {
|
||||
stderr += stderrDecoder.write(data);
|
||||
if (originalStdErrListener) {
|
||||
originalStdErrListener(data);
|
||||
}
|
||||
};
|
||||
const stdOutListener = (data) => {
|
||||
stdout += stdoutDecoder.write(data);
|
||||
if (originalStdoutListener) {
|
||||
originalStdoutListener(data);
|
||||
}
|
||||
};
|
||||
const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener });
|
||||
const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners }));
|
||||
//flush any remaining characters
|
||||
stdout += stdoutDecoder.end();
|
||||
stderr += stderrDecoder.end();
|
||||
return {
|
||||
exitCode,
|
||||
stdout,
|
||||
stderr
|
||||
};
|
||||
});
|
||||
}
|
||||
exports.getExecOutput = getExecOutput;
|
||||
//# sourceMappingURL=exec.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mDAA4C;AAE5C,iDAAkC;AAIlC;;;;;;;;;GASG;AACH,SAAsB,IAAI,CACxB,WAAmB,EACnB,IAAe,EACf,OAAqB;;QAErB,MAAM,WAAW,GAAG,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAA;QACpD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;SACpE;QACD,8CAA8C;QAC9C,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;QAC/B,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;QAC9C,MAAM,MAAM,GAAkB,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QACxE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;IACtB,CAAC;CAAA;AAdD,oBAcC;AAED;;;;;;;;;GASG;AAEH,SAAsB,aAAa,CACjC,WAAmB,EACnB,IAAe,EACf,OAAqB;;;QAErB,IAAI,MAAM,GAAG,EAAE,CAAA;QACf,IAAI,MAAM,GAAG,EAAE,CAAA;QAEf,2EAA2E;QAC3E,MAAM,aAAa,GAAG,IAAI,8BAAa,CAAC,MAAM,CAAC,CAAA;QAC/C,MAAM,aAAa,GAAG,IAAI,8BAAa,CAAC,MAAM,CAAC,CAAA;QAE/C,MAAM,sBAAsB,SAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,0CAAE,MAAM,CAAA;QACzD,MAAM,sBAAsB,SAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,0CAAE,MAAM,CAAA;QAEzD,MAAM,cAAc,GAAG,CAAC,IAAY,EAAQ,EAAE;YAC5C,MAAM,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;YACnC,IAAI,sBAAsB,EAAE;gBAC1B,sBAAsB,CAAC,IAAI,CAAC,CAAA;aAC7B;QACH,CAAC,CAAA;QAED,MAAM,cAAc,GAAG,CAAC,IAAY,EAAQ,EAAE;YAC5C,MAAM,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;YACnC,IAAI,sBAAsB,EAAE;gBAC1B,sBAAsB,CAAC,IAAI,CAAC,CAAA;aAC7B;QACH,CAAC,CAAA;QAED,MAAM,SAAS,mCACV,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,KACrB,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,cAAc,GACvB,CAAA;QAED,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,WAAW,EAAE,IAAI,kCAAM,OAAO,KAAE,SAAS,IAAE,CAAA;QAEvE,gCAAgC;QAChC,MAAM,IAAI,aAAa,CAAC,GAAG,EAAE,CAAA;QAC7B,MAAM,IAAI,aAAa,CAAC,GAAG,EAAE,CAAA;QAE7B,OAAO;YACL,QAAQ;YACR,MAAM;YACN,MAAM;SACP,CAAA;;CACF;AA9CD,sCA8CC"}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/// <reference types="node" />
|
||||
import * as stream from 'stream';
|
||||
/**
|
||||
* Interface for exec options
|
||||
*/
|
||||
export interface ExecOptions {
|
||||
/** optional working directory. defaults to current */
|
||||
cwd?: string;
|
||||
/** optional envvar dictionary. defaults to current process's env */
|
||||
env?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/** optional. defaults to false */
|
||||
silent?: boolean;
|
||||
/** optional out stream to use. Defaults to process.stdout */
|
||||
outStream?: stream.Writable;
|
||||
/** optional err stream to use. Defaults to process.stderr */
|
||||
errStream?: stream.Writable;
|
||||
/** optional. whether to skip quoting/escaping arguments if needed. defaults to false. */
|
||||
windowsVerbatimArguments?: boolean;
|
||||
/** optional. whether to fail if output to stderr. defaults to false */
|
||||
failOnStdErr?: boolean;
|
||||
/** optional. defaults to failing on non zero. ignore will not fail leaving it up to the caller */
|
||||
ignoreReturnCode?: boolean;
|
||||
/** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
|
||||
delay?: number;
|
||||
/** optional. input to write to the process on STDIN. */
|
||||
input?: Buffer;
|
||||
/** optional. Listeners for output. Callback functions that will be called on these events */
|
||||
listeners?: ExecListeners;
|
||||
}
|
||||
/**
|
||||
* Interface for the output of getExecOutput()
|
||||
*/
|
||||
export interface ExecOutput {
|
||||
/**The exit code of the process */
|
||||
exitCode: number;
|
||||
/**The entire stdout of the process as a string */
|
||||
stdout: string;
|
||||
/**The entire stderr of the process as a string */
|
||||
stderr: string;
|
||||
}
|
||||
/**
|
||||
* The user defined listeners for an exec call
|
||||
*/
|
||||
export interface ExecListeners {
|
||||
/** A call back for each buffer of stdout */
|
||||
stdout?: (data: Buffer) => void;
|
||||
/** A call back for each buffer of stderr */
|
||||
stderr?: (data: Buffer) => void;
|
||||
/** A call back for each line of stdout */
|
||||
stdline?: (data: string) => void;
|
||||
/** A call back for each line of stderr */
|
||||
errline?: (data: string) => void;
|
||||
/** A call back for each debug log */
|
||||
debug?: (data: string) => void;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=interfaces.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":""}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/// <reference types="node" />
|
||||
import * as events from 'events';
|
||||
import * as im from './interfaces';
|
||||
export declare class ToolRunner extends events.EventEmitter {
|
||||
constructor(toolPath: string, args?: string[], options?: im.ExecOptions);
|
||||
private toolPath;
|
||||
private args;
|
||||
private options;
|
||||
private _debug;
|
||||
private _getCommandString;
|
||||
private _processLineBuffer;
|
||||
private _getSpawnFileName;
|
||||
private _getSpawnArgs;
|
||||
private _endsWith;
|
||||
private _isCmdFile;
|
||||
private _windowsQuoteCmdArg;
|
||||
private _uvQuoteCmdArg;
|
||||
private _cloneExecOptions;
|
||||
private _getSpawnOptions;
|
||||
/**
|
||||
* Exec a tool.
|
||||
* Output will be streamed to the live console.
|
||||
* Returns promise with return code
|
||||
*
|
||||
* @param tool path to tool to exec
|
||||
* @param options optional exec options. See ExecOptions
|
||||
* @returns number
|
||||
*/
|
||||
exec(): Promise<number>;
|
||||
}
|
||||
/**
|
||||
* Convert an arg string to an array of args. Handles escaping
|
||||
*
|
||||
* @param argString string of arguments
|
||||
* @returns string[] array of arguments
|
||||
*/
|
||||
export declare function argStringToArray(argString: string): string[];
|
||||
+618
@@ -0,0 +1,618 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.argStringToArray = exports.ToolRunner = void 0;
|
||||
const os = __importStar(require("os"));
|
||||
const events = __importStar(require("events"));
|
||||
const child = __importStar(require("child_process"));
|
||||
const path = __importStar(require("path"));
|
||||
const io = __importStar(require("@actions/io"));
|
||||
const ioUtil = __importStar(require("@actions/io/lib/io-util"));
|
||||
const timers_1 = require("timers");
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
const IS_WINDOWS = process.platform === 'win32';
|
||||
/*
|
||||
* Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.
|
||||
*/
|
||||
class ToolRunner extends events.EventEmitter {
|
||||
constructor(toolPath, args, options) {
|
||||
super();
|
||||
if (!toolPath) {
|
||||
throw new Error("Parameter 'toolPath' cannot be null or empty.");
|
||||
}
|
||||
this.toolPath = toolPath;
|
||||
this.args = args || [];
|
||||
this.options = options || {};
|
||||
}
|
||||
_debug(message) {
|
||||
if (this.options.listeners && this.options.listeners.debug) {
|
||||
this.options.listeners.debug(message);
|
||||
}
|
||||
}
|
||||
_getCommandString(options, noPrefix) {
|
||||
const toolPath = this._getSpawnFileName();
|
||||
const args = this._getSpawnArgs(options);
|
||||
let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
|
||||
if (IS_WINDOWS) {
|
||||
// Windows + cmd file
|
||||
if (this._isCmdFile()) {
|
||||
cmd += toolPath;
|
||||
for (const a of args) {
|
||||
cmd += ` ${a}`;
|
||||
}
|
||||
}
|
||||
// Windows + verbatim
|
||||
else if (options.windowsVerbatimArguments) {
|
||||
cmd += `"${toolPath}"`;
|
||||
for (const a of args) {
|
||||
cmd += ` ${a}`;
|
||||
}
|
||||
}
|
||||
// Windows (regular)
|
||||
else {
|
||||
cmd += this._windowsQuoteCmdArg(toolPath);
|
||||
for (const a of args) {
|
||||
cmd += ` ${this._windowsQuoteCmdArg(a)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
// OSX/Linux - this can likely be improved with some form of quoting.
|
||||
// creating processes on Unix is fundamentally different than Windows.
|
||||
// on Unix, execvp() takes an arg array.
|
||||
cmd += toolPath;
|
||||
for (const a of args) {
|
||||
cmd += ` ${a}`;
|
||||
}
|
||||
}
|
||||
return cmd;
|
||||
}
|
||||
_processLineBuffer(data, strBuffer, onLine) {
|
||||
try {
|
||||
let s = strBuffer + data.toString();
|
||||
let n = s.indexOf(os.EOL);
|
||||
while (n > -1) {
|
||||
const line = s.substring(0, n);
|
||||
onLine(line);
|
||||
// the rest of the string ...
|
||||
s = s.substring(n + os.EOL.length);
|
||||
n = s.indexOf(os.EOL);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
catch (err) {
|
||||
// streaming lines to console is best effort. Don't fail a build.
|
||||
this._debug(`error processing line. Failed with error ${err}`);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
_getSpawnFileName() {
|
||||
if (IS_WINDOWS) {
|
||||
if (this._isCmdFile()) {
|
||||
return process.env['COMSPEC'] || 'cmd.exe';
|
||||
}
|
||||
}
|
||||
return this.toolPath;
|
||||
}
|
||||
_getSpawnArgs(options) {
|
||||
if (IS_WINDOWS) {
|
||||
if (this._isCmdFile()) {
|
||||
let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
|
||||
for (const a of this.args) {
|
||||
argline += ' ';
|
||||
argline += options.windowsVerbatimArguments
|
||||
? a
|
||||
: this._windowsQuoteCmdArg(a);
|
||||
}
|
||||
argline += '"';
|
||||
return [argline];
|
||||
}
|
||||
}
|
||||
return this.args;
|
||||
}
|
||||
_endsWith(str, end) {
|
||||
return str.endsWith(end);
|
||||
}
|
||||
_isCmdFile() {
|
||||
const upperToolPath = this.toolPath.toUpperCase();
|
||||
return (this._endsWith(upperToolPath, '.CMD') ||
|
||||
this._endsWith(upperToolPath, '.BAT'));
|
||||
}
|
||||
_windowsQuoteCmdArg(arg) {
|
||||
// for .exe, apply the normal quoting rules that libuv applies
|
||||
if (!this._isCmdFile()) {
|
||||
return this._uvQuoteCmdArg(arg);
|
||||
}
|
||||
// otherwise apply quoting rules specific to the cmd.exe command line parser.
|
||||
// the libuv rules are generic and are not designed specifically for cmd.exe
|
||||
// command line parser.
|
||||
//
|
||||
// for a detailed description of the cmd.exe command line parser, refer to
|
||||
// http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
|
||||
// need quotes for empty arg
|
||||
if (!arg) {
|
||||
return '""';
|
||||
}
|
||||
// determine whether the arg needs to be quoted
|
||||
const cmdSpecialChars = [
|
||||
' ',
|
||||
'\t',
|
||||
'&',
|
||||
'(',
|
||||
')',
|
||||
'[',
|
||||
']',
|
||||
'{',
|
||||
'}',
|
||||
'^',
|
||||
'=',
|
||||
';',
|
||||
'!',
|
||||
"'",
|
||||
'+',
|
||||
',',
|
||||
'`',
|
||||
'~',
|
||||
'|',
|
||||
'<',
|
||||
'>',
|
||||
'"'
|
||||
];
|
||||
let needsQuotes = false;
|
||||
for (const char of arg) {
|
||||
if (cmdSpecialChars.some(x => x === char)) {
|
||||
needsQuotes = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// short-circuit if quotes not needed
|
||||
if (!needsQuotes) {
|
||||
return arg;
|
||||
}
|
||||
// the following quoting rules are very similar to the rules that by libuv applies.
|
||||
//
|
||||
// 1) wrap the string in quotes
|
||||
//
|
||||
// 2) double-up quotes - i.e. " => ""
|
||||
//
|
||||
// this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
|
||||
// doesn't work well with a cmd.exe command line.
|
||||
//
|
||||
// note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
|
||||
// for example, the command line:
|
||||
// foo.exe "myarg:""my val"""
|
||||
// is parsed by a .NET console app into an arg array:
|
||||
// [ "myarg:\"my val\"" ]
|
||||
// which is the same end result when applying libuv quoting rules. although the actual
|
||||
// command line from libuv quoting rules would look like:
|
||||
// foo.exe "myarg:\"my val\""
|
||||
//
|
||||
// 3) double-up slashes that precede a quote,
|
||||
// e.g. hello \world => "hello \world"
|
||||
// hello\"world => "hello\\""world"
|
||||
// hello\\"world => "hello\\\\""world"
|
||||
// hello world\ => "hello world\\"
|
||||
//
|
||||
// technically this is not required for a cmd.exe command line, or the batch argument parser.
|
||||
// the reasons for including this as a .cmd quoting rule are:
|
||||
//
|
||||
// a) this is optimized for the scenario where the argument is passed from the .cmd file to an
|
||||
// external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
|
||||
//
|
||||
// b) it's what we've been doing previously (by deferring to node default behavior) and we
|
||||
// haven't heard any complaints about that aspect.
|
||||
//
|
||||
// note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
|
||||
// escaped when used on the command line directly - even though within a .cmd file % can be escaped
|
||||
// by using %%.
|
||||
//
|
||||
// the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
|
||||
// the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
|
||||
//
|
||||
// one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
|
||||
// often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
|
||||
// variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
|
||||
// to an external program.
|
||||
//
|
||||
// an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
|
||||
// % can be escaped within a .cmd file.
|
||||
let reverse = '"';
|
||||
let quoteHit = true;
|
||||
for (let i = arg.length; i > 0; i--) {
|
||||
// walk the string in reverse
|
||||
reverse += arg[i - 1];
|
||||
if (quoteHit && arg[i - 1] === '\\') {
|
||||
reverse += '\\'; // double the slash
|
||||
}
|
||||
else if (arg[i - 1] === '"') {
|
||||
quoteHit = true;
|
||||
reverse += '"'; // double the quote
|
||||
}
|
||||
else {
|
||||
quoteHit = false;
|
||||
}
|
||||
}
|
||||
reverse += '"';
|
||||
return reverse
|
||||
.split('')
|
||||
.reverse()
|
||||
.join('');
|
||||
}
|
||||
_uvQuoteCmdArg(arg) {
|
||||
// Tool runner wraps child_process.spawn() and needs to apply the same quoting as
|
||||
// Node in certain cases where the undocumented spawn option windowsVerbatimArguments
|
||||
// is used.
|
||||
//
|
||||
// Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
|
||||
// see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
|
||||
// pasting copyright notice from Node within this function:
|
||||
//
|
||||
// Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to
|
||||
// deal in the Software without restriction, including without limitation the
|
||||
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
// sell copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
// IN THE SOFTWARE.
|
||||
if (!arg) {
|
||||
// Need double quotation for empty argument
|
||||
return '""';
|
||||
}
|
||||
if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
|
||||
// No quotation needed
|
||||
return arg;
|
||||
}
|
||||
if (!arg.includes('"') && !arg.includes('\\')) {
|
||||
// No embedded double quotes or backslashes, so I can just wrap
|
||||
// quote marks around the whole thing.
|
||||
return `"${arg}"`;
|
||||
}
|
||||
// Expected input/output:
|
||||
// input : hello"world
|
||||
// output: "hello\"world"
|
||||
// input : hello""world
|
||||
// output: "hello\"\"world"
|
||||
// input : hello\world
|
||||
// output: hello\world
|
||||
// input : hello\\world
|
||||
// output: hello\\world
|
||||
// input : hello\"world
|
||||
// output: "hello\\\"world"
|
||||
// input : hello\\"world
|
||||
// output: "hello\\\\\"world"
|
||||
// input : hello world\
|
||||
// output: "hello world\\" - note the comment in libuv actually reads "hello world\"
|
||||
// but it appears the comment is wrong, it should be "hello world\\"
|
||||
let reverse = '"';
|
||||
let quoteHit = true;
|
||||
for (let i = arg.length; i > 0; i--) {
|
||||
// walk the string in reverse
|
||||
reverse += arg[i - 1];
|
||||
if (quoteHit && arg[i - 1] === '\\') {
|
||||
reverse += '\\';
|
||||
}
|
||||
else if (arg[i - 1] === '"') {
|
||||
quoteHit = true;
|
||||
reverse += '\\';
|
||||
}
|
||||
else {
|
||||
quoteHit = false;
|
||||
}
|
||||
}
|
||||
reverse += '"';
|
||||
return reverse
|
||||
.split('')
|
||||
.reverse()
|
||||
.join('');
|
||||
}
|
||||
_cloneExecOptions(options) {
|
||||
options = options || {};
|
||||
const result = {
|
||||
cwd: options.cwd || process.cwd(),
|
||||
env: options.env || process.env,
|
||||
silent: options.silent || false,
|
||||
windowsVerbatimArguments: options.windowsVerbatimArguments || false,
|
||||
failOnStdErr: options.failOnStdErr || false,
|
||||
ignoreReturnCode: options.ignoreReturnCode || false,
|
||||
delay: options.delay || 10000
|
||||
};
|
||||
result.outStream = options.outStream || process.stdout;
|
||||
result.errStream = options.errStream || process.stderr;
|
||||
return result;
|
||||
}
|
||||
_getSpawnOptions(options, toolPath) {
|
||||
options = options || {};
|
||||
const result = {};
|
||||
result.cwd = options.cwd;
|
||||
result.env = options.env;
|
||||
result['windowsVerbatimArguments'] =
|
||||
options.windowsVerbatimArguments || this._isCmdFile();
|
||||
if (options.windowsVerbatimArguments) {
|
||||
result.argv0 = `"${toolPath}"`;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Exec a tool.
|
||||
* Output will be streamed to the live console.
|
||||
* Returns promise with return code
|
||||
*
|
||||
* @param tool path to tool to exec
|
||||
* @param options optional exec options. See ExecOptions
|
||||
* @returns number
|
||||
*/
|
||||
exec() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
// root the tool path if it is unrooted and contains relative pathing
|
||||
if (!ioUtil.isRooted(this.toolPath) &&
|
||||
(this.toolPath.includes('/') ||
|
||||
(IS_WINDOWS && this.toolPath.includes('\\')))) {
|
||||
// prefer options.cwd if it is specified, however options.cwd may also need to be rooted
|
||||
this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
|
||||
}
|
||||
// if the tool is only a file name, then resolve it from the PATH
|
||||
// otherwise verify it exists (add extension on Windows if necessary)
|
||||
this.toolPath = yield io.which(this.toolPath, true);
|
||||
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
||||
this._debug(`exec tool: ${this.toolPath}`);
|
||||
this._debug('arguments:');
|
||||
for (const arg of this.args) {
|
||||
this._debug(` ${arg}`);
|
||||
}
|
||||
const optionsNonNull = this._cloneExecOptions(this.options);
|
||||
if (!optionsNonNull.silent && optionsNonNull.outStream) {
|
||||
optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);
|
||||
}
|
||||
const state = new ExecState(optionsNonNull, this.toolPath);
|
||||
state.on('debug', (message) => {
|
||||
this._debug(message);
|
||||
});
|
||||
if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) {
|
||||
return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));
|
||||
}
|
||||
const fileName = this._getSpawnFileName();
|
||||
const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
|
||||
let stdbuffer = '';
|
||||
if (cp.stdout) {
|
||||
cp.stdout.on('data', (data) => {
|
||||
if (this.options.listeners && this.options.listeners.stdout) {
|
||||
this.options.listeners.stdout(data);
|
||||
}
|
||||
if (!optionsNonNull.silent && optionsNonNull.outStream) {
|
||||
optionsNonNull.outStream.write(data);
|
||||
}
|
||||
stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => {
|
||||
if (this.options.listeners && this.options.listeners.stdline) {
|
||||
this.options.listeners.stdline(line);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
let errbuffer = '';
|
||||
if (cp.stderr) {
|
||||
cp.stderr.on('data', (data) => {
|
||||
state.processStderr = true;
|
||||
if (this.options.listeners && this.options.listeners.stderr) {
|
||||
this.options.listeners.stderr(data);
|
||||
}
|
||||
if (!optionsNonNull.silent &&
|
||||
optionsNonNull.errStream &&
|
||||
optionsNonNull.outStream) {
|
||||
const s = optionsNonNull.failOnStdErr
|
||||
? optionsNonNull.errStream
|
||||
: optionsNonNull.outStream;
|
||||
s.write(data);
|
||||
}
|
||||
errbuffer = this._processLineBuffer(data, errbuffer, (line) => {
|
||||
if (this.options.listeners && this.options.listeners.errline) {
|
||||
this.options.listeners.errline(line);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
cp.on('error', (err) => {
|
||||
state.processError = err.message;
|
||||
state.processExited = true;
|
||||
state.processClosed = true;
|
||||
state.CheckComplete();
|
||||
});
|
||||
cp.on('exit', (code) => {
|
||||
state.processExitCode = code;
|
||||
state.processExited = true;
|
||||
this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
|
||||
state.CheckComplete();
|
||||
});
|
||||
cp.on('close', (code) => {
|
||||
state.processExitCode = code;
|
||||
state.processExited = true;
|
||||
state.processClosed = true;
|
||||
this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
|
||||
state.CheckComplete();
|
||||
});
|
||||
state.on('done', (error, exitCode) => {
|
||||
if (stdbuffer.length > 0) {
|
||||
this.emit('stdline', stdbuffer);
|
||||
}
|
||||
if (errbuffer.length > 0) {
|
||||
this.emit('errline', errbuffer);
|
||||
}
|
||||
cp.removeAllListeners();
|
||||
if (error) {
|
||||
reject(error);
|
||||
}
|
||||
else {
|
||||
resolve(exitCode);
|
||||
}
|
||||
});
|
||||
if (this.options.input) {
|
||||
if (!cp.stdin) {
|
||||
throw new Error('child process missing stdin');
|
||||
}
|
||||
cp.stdin.end(this.options.input);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.ToolRunner = ToolRunner;
|
||||
/**
|
||||
* Convert an arg string to an array of args. Handles escaping
|
||||
*
|
||||
* @param argString string of arguments
|
||||
* @returns string[] array of arguments
|
||||
*/
|
||||
function argStringToArray(argString) {
|
||||
const args = [];
|
||||
let inQuotes = false;
|
||||
let escaped = false;
|
||||
let arg = '';
|
||||
function append(c) {
|
||||
// we only escape double quotes.
|
||||
if (escaped && c !== '"') {
|
||||
arg += '\\';
|
||||
}
|
||||
arg += c;
|
||||
escaped = false;
|
||||
}
|
||||
for (let i = 0; i < argString.length; i++) {
|
||||
const c = argString.charAt(i);
|
||||
if (c === '"') {
|
||||
if (!escaped) {
|
||||
inQuotes = !inQuotes;
|
||||
}
|
||||
else {
|
||||
append(c);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c === '\\' && escaped) {
|
||||
append(c);
|
||||
continue;
|
||||
}
|
||||
if (c === '\\' && inQuotes) {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if (c === ' ' && !inQuotes) {
|
||||
if (arg.length > 0) {
|
||||
args.push(arg);
|
||||
arg = '';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
append(c);
|
||||
}
|
||||
if (arg.length > 0) {
|
||||
args.push(arg.trim());
|
||||
}
|
||||
return args;
|
||||
}
|
||||
exports.argStringToArray = argStringToArray;
|
||||
class ExecState extends events.EventEmitter {
|
||||
constructor(options, toolPath) {
|
||||
super();
|
||||
this.processClosed = false; // tracks whether the process has exited and stdio is closed
|
||||
this.processError = '';
|
||||
this.processExitCode = 0;
|
||||
this.processExited = false; // tracks whether the process has exited
|
||||
this.processStderr = false; // tracks whether stderr was written to
|
||||
this.delay = 10000; // 10 seconds
|
||||
this.done = false;
|
||||
this.timeout = null;
|
||||
if (!toolPath) {
|
||||
throw new Error('toolPath must not be empty');
|
||||
}
|
||||
this.options = options;
|
||||
this.toolPath = toolPath;
|
||||
if (options.delay) {
|
||||
this.delay = options.delay;
|
||||
}
|
||||
}
|
||||
CheckComplete() {
|
||||
if (this.done) {
|
||||
return;
|
||||
}
|
||||
if (this.processClosed) {
|
||||
this._setResult();
|
||||
}
|
||||
else if (this.processExited) {
|
||||
this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this);
|
||||
}
|
||||
}
|
||||
_debug(message) {
|
||||
this.emit('debug', message);
|
||||
}
|
||||
_setResult() {
|
||||
// determine whether there is an error
|
||||
let error;
|
||||
if (this.processExited) {
|
||||
if (this.processError) {
|
||||
error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);
|
||||
}
|
||||
else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {
|
||||
error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);
|
||||
}
|
||||
else if (this.processStderr && this.options.failOnStdErr) {
|
||||
error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);
|
||||
}
|
||||
}
|
||||
// clear the timeout
|
||||
if (this.timeout) {
|
||||
clearTimeout(this.timeout);
|
||||
this.timeout = null;
|
||||
}
|
||||
this.done = true;
|
||||
this.emit('done', error, this.processExitCode);
|
||||
}
|
||||
static HandleTimeout(state) {
|
||||
if (state.done) {
|
||||
return;
|
||||
}
|
||||
if (!state.processClosed && state.processExited) {
|
||||
const message = `The STDIO streams did not close within ${state.delay /
|
||||
1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;
|
||||
state._debug(message);
|
||||
}
|
||||
state._setResult();
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=toolrunner.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@actions/exec",
|
||||
"version": "1.1.0",
|
||||
"description": "Actions exec lib",
|
||||
"keywords": [
|
||||
"github",
|
||||
"actions",
|
||||
"exec"
|
||||
],
|
||||
"homepage": "https://github.com/actions/toolkit/tree/main/packages/exec",
|
||||
"license": "MIT",
|
||||
"main": "lib/exec.js",
|
||||
"types": "lib/exec.d.ts",
|
||||
"directories": {
|
||||
"lib": "lib",
|
||||
"test": "__tests__"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"!.DS_Store"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/actions/toolkit.git",
|
||||
"directory": "packages/exec"
|
||||
},
|
||||
"scripts": {
|
||||
"audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/actions/toolkit/issues"
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/io": "^1.0.1"
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright 2019 GitHub
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# `@actions/io`
|
||||
|
||||
> Core functions for cli filesystem scenarios
|
||||
|
||||
## Usage
|
||||
|
||||
#### mkdir -p
|
||||
|
||||
Recursively make a directory. Follows rules specified in [man mkdir](https://linux.die.net/man/1/mkdir) with the `-p` option specified:
|
||||
|
||||
```js
|
||||
const io = require('@actions/io');
|
||||
|
||||
await io.mkdirP('path/to/make');
|
||||
```
|
||||
|
||||
#### cp/mv
|
||||
|
||||
Copy or move files or folders. Follows rules specified in [man cp](https://linux.die.net/man/1/cp) and [man mv](https://linux.die.net/man/1/mv):
|
||||
|
||||
```js
|
||||
const io = require('@actions/io');
|
||||
|
||||
// Recursive must be true for directories
|
||||
const options = { recursive: true, force: false }
|
||||
|
||||
await io.cp('path/to/directory', 'path/to/dest', options);
|
||||
await io.mv('path/to/file', 'path/to/dest');
|
||||
```
|
||||
|
||||
#### rm -rf
|
||||
|
||||
Remove a file or folder recursively. Follows rules specified in [man rm](https://linux.die.net/man/1/rm) with the `-r` and `-f` rules specified.
|
||||
|
||||
```js
|
||||
const io = require('@actions/io');
|
||||
|
||||
await io.rmRF('path/to/directory');
|
||||
await io.rmRF('path/to/file');
|
||||
```
|
||||
|
||||
#### which
|
||||
|
||||
Get the path to a tool and resolves via paths. Follows the rules specified in [man which](https://linux.die.net/man/1/which).
|
||||
|
||||
```js
|
||||
const exec = require('@actions/exec');
|
||||
const io = require('@actions/io');
|
||||
|
||||
const pythonPath: string = await io.which('python', true)
|
||||
|
||||
await exec.exec(`"${pythonPath}"`, ['main.py']);
|
||||
```
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/// <reference types="node" />
|
||||
import * as fs from 'fs';
|
||||
export declare const chmod: typeof fs.promises.chmod, copyFile: typeof fs.promises.copyFile, lstat: typeof fs.promises.lstat, mkdir: typeof fs.promises.mkdir, readdir: typeof fs.promises.readdir, readlink: typeof fs.promises.readlink, rename: typeof fs.promises.rename, rmdir: typeof fs.promises.rmdir, stat: typeof fs.promises.stat, symlink: typeof fs.promises.symlink, unlink: typeof fs.promises.unlink;
|
||||
export declare const IS_WINDOWS: boolean;
|
||||
export declare function exists(fsPath: string): Promise<boolean>;
|
||||
export declare function isDirectory(fsPath: string, useStat?: boolean): Promise<boolean>;
|
||||
/**
|
||||
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
|
||||
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
|
||||
*/
|
||||
export declare function isRooted(p: string): boolean;
|
||||
/**
|
||||
* Best effort attempt to determine whether a file exists and is executable.
|
||||
* @param filePath file path to check
|
||||
* @param extensions additional file extensions to try
|
||||
* @return if file exists and is executable, returns the file path. otherwise empty string.
|
||||
*/
|
||||
export declare function tryGetExecutablePath(filePath: string, extensions: string[]): Promise<string>;
|
||||
export declare function getCmdPath(): string;
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var _a;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rename = exports.readlink = exports.readdir = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0;
|
||||
const fs = __importStar(require("fs"));
|
||||
const path = __importStar(require("path"));
|
||||
_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
|
||||
exports.IS_WINDOWS = process.platform === 'win32';
|
||||
function exists(fsPath) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
yield exports.stat(fsPath);
|
||||
}
|
||||
catch (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
return false;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
exports.exists = exists;
|
||||
function isDirectory(fsPath, useStat = false) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);
|
||||
return stats.isDirectory();
|
||||
});
|
||||
}
|
||||
exports.isDirectory = isDirectory;
|
||||
/**
|
||||
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
|
||||
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
|
||||
*/
|
||||
function isRooted(p) {
|
||||
p = normalizeSeparators(p);
|
||||
if (!p) {
|
||||
throw new Error('isRooted() parameter "p" cannot be empty');
|
||||
}
|
||||
if (exports.IS_WINDOWS) {
|
||||
return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
|
||||
); // e.g. C: or C:\hello
|
||||
}
|
||||
return p.startsWith('/');
|
||||
}
|
||||
exports.isRooted = isRooted;
|
||||
/**
|
||||
* Best effort attempt to determine whether a file exists and is executable.
|
||||
* @param filePath file path to check
|
||||
* @param extensions additional file extensions to try
|
||||
* @return if file exists and is executable, returns the file path. otherwise empty string.
|
||||
*/
|
||||
function tryGetExecutablePath(filePath, extensions) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let stats = undefined;
|
||||
try {
|
||||
// test file exists
|
||||
stats = yield exports.stat(filePath);
|
||||
}
|
||||
catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
|
||||
}
|
||||
}
|
||||
if (stats && stats.isFile()) {
|
||||
if (exports.IS_WINDOWS) {
|
||||
// on Windows, test for valid extension
|
||||
const upperExt = path.extname(filePath).toUpperCase();
|
||||
if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (isUnixExecutable(stats)) {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
// try each extension
|
||||
const originalFilePath = filePath;
|
||||
for (const extension of extensions) {
|
||||
filePath = originalFilePath + extension;
|
||||
stats = undefined;
|
||||
try {
|
||||
stats = yield exports.stat(filePath);
|
||||
}
|
||||
catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
|
||||
}
|
||||
}
|
||||
if (stats && stats.isFile()) {
|
||||
if (exports.IS_WINDOWS) {
|
||||
// preserve the case of the actual file (since an extension was appended)
|
||||
try {
|
||||
const directory = path.dirname(filePath);
|
||||
const upperName = path.basename(filePath).toUpperCase();
|
||||
for (const actualName of yield exports.readdir(directory)) {
|
||||
if (upperName === actualName.toUpperCase()) {
|
||||
filePath = path.join(directory, actualName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
else {
|
||||
if (isUnixExecutable(stats)) {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
});
|
||||
}
|
||||
exports.tryGetExecutablePath = tryGetExecutablePath;
|
||||
function normalizeSeparators(p) {
|
||||
p = p || '';
|
||||
if (exports.IS_WINDOWS) {
|
||||
// convert slashes on Windows
|
||||
p = p.replace(/\//g, '\\');
|
||||
// remove redundant slashes
|
||||
return p.replace(/\\\\+/g, '\\');
|
||||
}
|
||||
// remove redundant slashes
|
||||
return p.replace(/\/\/+/g, '/');
|
||||
}
|
||||
// on Mac/Linux, test the execute bit
|
||||
// R W X R W X R W X
|
||||
// 256 128 64 32 16 8 4 2 1
|
||||
function isUnixExecutable(stats) {
|
||||
return ((stats.mode & 1) > 0 ||
|
||||
((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||
|
||||
((stats.mode & 64) > 0 && stats.uid === process.getuid()));
|
||||
}
|
||||
// Get the path of cmd.exe in windows
|
||||
function getCmdPath() {
|
||||
var _a;
|
||||
return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`;
|
||||
}
|
||||
exports.getCmdPath = getCmdPath;
|
||||
//# sourceMappingURL=io-util.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"io-util.js","sourceRoot":"","sources":["../src/io-util.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAwB;AACxB,2CAA4B;AAEf,KAYT,EAAE,CAAC,QAAQ,EAXb,aAAK,aACL,gBAAQ,gBACR,aAAK,aACL,aAAK,aACL,eAAO,eACP,gBAAQ,gBACR,cAAM,cACN,aAAK,aACL,YAAI,YACJ,eAAO,eACP,cAAM,aACO;AAEF,QAAA,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAA;AAEtD,SAAsB,MAAM,CAAC,MAAc;;QACzC,IAAI;YACF,MAAM,YAAI,CAAC,MAAM,CAAC,CAAA;SACnB;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACzB,OAAO,KAAK,CAAA;aACb;YAED,MAAM,GAAG,CAAA;SACV;QAED,OAAO,IAAI,CAAA;IACb,CAAC;CAAA;AAZD,wBAYC;AAED,SAAsB,WAAW,CAC/B,MAAc,EACd,OAAO,GAAG,KAAK;;QAEf,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,YAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,aAAK,CAAC,MAAM,CAAC,CAAA;QAChE,OAAO,KAAK,CAAC,WAAW,EAAE,CAAA;IAC5B,CAAC;CAAA;AAND,kCAMC;AAED;;;GAGG;AACH,SAAgB,QAAQ,CAAC,CAAS;IAChC,CAAC,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAA;IAC1B,IAAI,CAAC,CAAC,EAAE;QACN,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;KAC5D;IAED,IAAI,kBAAU,EAAE;QACd,OAAO,CACL,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,8BAA8B;SACxE,CAAA,CAAC,sBAAsB;KACzB;IAED,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC;AAbD,4BAaC;AAED;;;;;GAKG;AACH,SAAsB,oBAAoB,CACxC,QAAgB,EAChB,UAAoB;;QAEpB,IAAI,KAAK,GAAyB,SAAS,CAAA;QAC3C,IAAI;YACF,mBAAmB;YACnB,KAAK,GAAG,MAAM,YAAI,CAAC,QAAQ,CAAC,CAAA;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACzB,sCAAsC;gBACtC,OAAO,CAAC,GAAG,CACT,uEAAuE,QAAQ,MAAM,GAAG,EAAE,CAC3F,CAAA;aACF;SACF;QACD,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;YAC3B,IAAI,kBAAU,EAAE;gBACd,uCAAuC;gBACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAA;gBACrD,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,WAAW,EAAE,KAAK,QAAQ,CAAC,EAAE;oBACpE,OAAO,QAAQ,CAAA;iBAChB;aACF;iBAAM;gBACL,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;oBAC3B,OAAO,QAAQ,CAAA;iBAChB;aACF;SACF;QAED,qBAAqB;QACrB,MAAM,gBAAgB,GAAG,QAAQ,CAAA;QACjC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE;YAClC,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CAAA;YAEvC,KAAK,GAAG,SAAS,CAAA;YACjB,IAAI;gBACF,KAAK,GAAG,MAAM,YAAI,CAAC,QAAQ,CAAC,CAAA;aAC7B;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;oBACzB,sCAAsC;oBACtC,OAAO,CAAC,GAAG,CACT,uEAAuE,QAAQ,MAAM,GAAG,EAAE,CAC3F,CAAA;iBACF;aACF;YAED,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;gBAC3B,IAAI,kBAAU,EAAE;oBACd,yEAAyE;oBACzE,IAAI;wBACF,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;wBACxC,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAA;wBACvD,KAAK,MAAM,UAAU,IAAI,MAAM,eAAO,CAAC,SAAS,CAAC,EAAE;4BACjD,IAAI,SAAS,KAAK,UAAU,CAAC,WAAW,EAAE,EAAE;gCAC1C,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;gCAC3C,MAAK;6BACN;yBACF;qBACF;oBAAC,OAAO,GAAG,EAAE;wBACZ,sCAAsC;wBACtC,OAAO,CAAC,GAAG,CACT,yEAAyE,QAAQ,MAAM,GAAG,EAAE,CAC7F,CAAA;qBACF;oBAED,OAAO,QAAQ,CAAA;iBAChB;qBAAM;oBACL,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;wBAC3B,OAAO,QAAQ,CAAA;qBAChB;iBACF;aACF;SACF;QAED,OAAO,EAAE,CAAA;IACX,CAAC;CAAA;AA5ED,oDA4EC;AAED,SAAS,mBAAmB,CAAC,CAAS;IACpC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;IACX,IAAI,kBAAU,EAAE;QACd,6BAA6B;QAC7B,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QAE1B,2BAA2B;QAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;KACjC;IAED,2BAA2B;IAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjC,CAAC;AAED,qCAAqC;AACrC,6BAA6B;AAC7B,6BAA6B;AAC7B,SAAS,gBAAgB,CAAC,KAAe;IACvC,OAAO,CACL,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC;QACpB,CAAC,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC;QACxD,CAAC,CAAC,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAC1D,CAAA;AACH,CAAC;AAED,qCAAqC;AACrC,SAAgB,UAAU;;IACxB,aAAO,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,mCAAI,SAAS,CAAA;AAC5C,CAAC;AAFD,gCAEC"}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Interface for cp/mv options
|
||||
*/
|
||||
export interface CopyOptions {
|
||||
/** Optional. Whether to recursively copy all subdirectories. Defaults to false */
|
||||
recursive?: boolean;
|
||||
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
|
||||
force?: boolean;
|
||||
/** Optional. Whether to copy the source directory along with all the files. Only takes effect when recursive=true and copying a directory. Default is true*/
|
||||
copySourceDirectory?: boolean;
|
||||
}
|
||||
/**
|
||||
* Interface for cp/mv options
|
||||
*/
|
||||
export interface MoveOptions {
|
||||
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
|
||||
force?: boolean;
|
||||
}
|
||||
/**
|
||||
* Copies a file or folder.
|
||||
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
|
||||
*
|
||||
* @param source source path
|
||||
* @param dest destination path
|
||||
* @param options optional. See CopyOptions.
|
||||
*/
|
||||
export declare function cp(source: string, dest: string, options?: CopyOptions): Promise<void>;
|
||||
/**
|
||||
* Moves a path.
|
||||
*
|
||||
* @param source source path
|
||||
* @param dest destination path
|
||||
* @param options optional. See MoveOptions.
|
||||
*/
|
||||
export declare function mv(source: string, dest: string, options?: MoveOptions): Promise<void>;
|
||||
/**
|
||||
* Remove a path recursively with force
|
||||
*
|
||||
* @param inputPath path to remove
|
||||
*/
|
||||
export declare function rmRF(inputPath: string): Promise<void>;
|
||||
/**
|
||||
* Make a directory. Creates the full path with folders in between
|
||||
* Will throw if it fails
|
||||
*
|
||||
* @param fsPath path to create
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
export declare function mkdirP(fsPath: string): Promise<void>;
|
||||
/**
|
||||
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
|
||||
* If you check and the tool does not exist, it will throw.
|
||||
*
|
||||
* @param tool name of the tool
|
||||
* @param check whether to check if tool exists
|
||||
* @returns Promise<string> path to tool
|
||||
*/
|
||||
export declare function which(tool: string, check?: boolean): Promise<string>;
|
||||
/**
|
||||
* Returns a list of all occurrences of the given tool on the system path.
|
||||
*
|
||||
* @returns Promise<string[]> the paths of the tool
|
||||
*/
|
||||
export declare function findInPath(tool: string): Promise<string[]>;
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0;
|
||||
const assert_1 = require("assert");
|
||||
const childProcess = __importStar(require("child_process"));
|
||||
const path = __importStar(require("path"));
|
||||
const util_1 = require("util");
|
||||
const ioUtil = __importStar(require("./io-util"));
|
||||
const exec = util_1.promisify(childProcess.exec);
|
||||
const execFile = util_1.promisify(childProcess.execFile);
|
||||
/**
|
||||
* Copies a file or folder.
|
||||
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
|
||||
*
|
||||
* @param source source path
|
||||
* @param dest destination path
|
||||
* @param options optional. See CopyOptions.
|
||||
*/
|
||||
function cp(source, dest, options = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const { force, recursive, copySourceDirectory } = readCopyOptions(options);
|
||||
const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;
|
||||
// Dest is an existing file, but not forcing
|
||||
if (destStat && destStat.isFile() && !force) {
|
||||
return;
|
||||
}
|
||||
// If dest is an existing directory, should copy inside.
|
||||
const newDest = destStat && destStat.isDirectory() && copySourceDirectory
|
||||
? path.join(dest, path.basename(source))
|
||||
: dest;
|
||||
if (!(yield ioUtil.exists(source))) {
|
||||
throw new Error(`no such file or directory: ${source}`);
|
||||
}
|
||||
const sourceStat = yield ioUtil.stat(source);
|
||||
if (sourceStat.isDirectory()) {
|
||||
if (!recursive) {
|
||||
throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
|
||||
}
|
||||
else {
|
||||
yield cpDirRecursive(source, newDest, 0, force);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (path.relative(source, newDest) === '') {
|
||||
// a file cannot be copied to itself
|
||||
throw new Error(`'${newDest}' and '${source}' are the same file`);
|
||||
}
|
||||
yield copyFile(source, newDest, force);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.cp = cp;
|
||||
/**
|
||||
* Moves a path.
|
||||
*
|
||||
* @param source source path
|
||||
* @param dest destination path
|
||||
* @param options optional. See MoveOptions.
|
||||
*/
|
||||
function mv(source, dest, options = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (yield ioUtil.exists(dest)) {
|
||||
let destExists = true;
|
||||
if (yield ioUtil.isDirectory(dest)) {
|
||||
// If dest is directory copy src into dest
|
||||
dest = path.join(dest, path.basename(source));
|
||||
destExists = yield ioUtil.exists(dest);
|
||||
}
|
||||
if (destExists) {
|
||||
if (options.force == null || options.force) {
|
||||
yield rmRF(dest);
|
||||
}
|
||||
else {
|
||||
throw new Error('Destination already exists');
|
||||
}
|
||||
}
|
||||
}
|
||||
yield mkdirP(path.dirname(dest));
|
||||
yield ioUtil.rename(source, dest);
|
||||
});
|
||||
}
|
||||
exports.mv = mv;
|
||||
/**
|
||||
* Remove a path recursively with force
|
||||
*
|
||||
* @param inputPath path to remove
|
||||
*/
|
||||
function rmRF(inputPath) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (ioUtil.IS_WINDOWS) {
|
||||
// Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another
|
||||
// program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.
|
||||
// Check for invalid characters
|
||||
// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
|
||||
if (/[*"<>|]/.test(inputPath)) {
|
||||
throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows');
|
||||
}
|
||||
try {
|
||||
const cmdPath = ioUtil.getCmdPath();
|
||||
if (yield ioUtil.isDirectory(inputPath, true)) {
|
||||
yield exec(`${cmdPath} /s /c "rd /s /q "%inputPath%""`, {
|
||||
env: { inputPath }
|
||||
});
|
||||
}
|
||||
else {
|
||||
yield exec(`${cmdPath} /s /c "del /f /a "%inputPath%""`, {
|
||||
env: { inputPath }
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
||||
// other errors are valid
|
||||
if (err.code !== 'ENOENT')
|
||||
throw err;
|
||||
}
|
||||
// Shelling out fails to remove a symlink folder with missing source, this unlink catches that
|
||||
try {
|
||||
yield ioUtil.unlink(inputPath);
|
||||
}
|
||||
catch (err) {
|
||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
||||
// other errors are valid
|
||||
if (err.code !== 'ENOENT')
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
else {
|
||||
let isDir = false;
|
||||
try {
|
||||
isDir = yield ioUtil.isDirectory(inputPath);
|
||||
}
|
||||
catch (err) {
|
||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
||||
// other errors are valid
|
||||
if (err.code !== 'ENOENT')
|
||||
throw err;
|
||||
return;
|
||||
}
|
||||
if (isDir) {
|
||||
yield execFile(`rm`, [`-rf`, `${inputPath}`]);
|
||||
}
|
||||
else {
|
||||
yield ioUtil.unlink(inputPath);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.rmRF = rmRF;
|
||||
/**
|
||||
* Make a directory. Creates the full path with folders in between
|
||||
* Will throw if it fails
|
||||
*
|
||||
* @param fsPath path to create
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
function mkdirP(fsPath) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
assert_1.ok(fsPath, 'a path argument must be provided');
|
||||
yield ioUtil.mkdir(fsPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
exports.mkdirP = mkdirP;
|
||||
/**
|
||||
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
|
||||
* If you check and the tool does not exist, it will throw.
|
||||
*
|
||||
* @param tool name of the tool
|
||||
* @param check whether to check if tool exists
|
||||
* @returns Promise<string> path to tool
|
||||
*/
|
||||
function which(tool, check) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!tool) {
|
||||
throw new Error("parameter 'tool' is required");
|
||||
}
|
||||
// recursive when check=true
|
||||
if (check) {
|
||||
const result = yield which(tool, false);
|
||||
if (!result) {
|
||||
if (ioUtil.IS_WINDOWS) {
|
||||
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
|
||||
}
|
||||
else {
|
||||
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
const matches = yield findInPath(tool);
|
||||
if (matches && matches.length > 0) {
|
||||
return matches[0];
|
||||
}
|
||||
return '';
|
||||
});
|
||||
}
|
||||
exports.which = which;
|
||||
/**
|
||||
* Returns a list of all occurrences of the given tool on the system path.
|
||||
*
|
||||
* @returns Promise<string[]> the paths of the tool
|
||||
*/
|
||||
function findInPath(tool) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!tool) {
|
||||
throw new Error("parameter 'tool' is required");
|
||||
}
|
||||
// build the list of extensions to try
|
||||
const extensions = [];
|
||||
if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) {
|
||||
for (const extension of process.env['PATHEXT'].split(path.delimiter)) {
|
||||
if (extension) {
|
||||
extensions.push(extension);
|
||||
}
|
||||
}
|
||||
}
|
||||
// if it's rooted, return it if exists. otherwise return empty.
|
||||
if (ioUtil.isRooted(tool)) {
|
||||
const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);
|
||||
if (filePath) {
|
||||
return [filePath];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
// if any path separators, return empty
|
||||
if (tool.includes(path.sep)) {
|
||||
return [];
|
||||
}
|
||||
// build the list of directories
|
||||
//
|
||||
// Note, technically "where" checks the current directory on Windows. From a toolkit perspective,
|
||||
// it feels like we should not do this. Checking the current directory seems like more of a use
|
||||
// case of a shell, and the which() function exposed by the toolkit should strive for consistency
|
||||
// across platforms.
|
||||
const directories = [];
|
||||
if (process.env.PATH) {
|
||||
for (const p of process.env.PATH.split(path.delimiter)) {
|
||||
if (p) {
|
||||
directories.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
// find all matches
|
||||
const matches = [];
|
||||
for (const directory of directories) {
|
||||
const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions);
|
||||
if (filePath) {
|
||||
matches.push(filePath);
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
});
|
||||
}
|
||||
exports.findInPath = findInPath;
|
||||
function readCopyOptions(options) {
|
||||
const force = options.force == null ? true : options.force;
|
||||
const recursive = Boolean(options.recursive);
|
||||
const copySourceDirectory = options.copySourceDirectory == null
|
||||
? true
|
||||
: Boolean(options.copySourceDirectory);
|
||||
return { force, recursive, copySourceDirectory };
|
||||
}
|
||||
function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
// Ensure there is not a run away recursive copy
|
||||
if (currentDepth >= 255)
|
||||
return;
|
||||
currentDepth++;
|
||||
yield mkdirP(destDir);
|
||||
const files = yield ioUtil.readdir(sourceDir);
|
||||
for (const fileName of files) {
|
||||
const srcFile = `${sourceDir}/${fileName}`;
|
||||
const destFile = `${destDir}/${fileName}`;
|
||||
const srcFileStat = yield ioUtil.lstat(srcFile);
|
||||
if (srcFileStat.isDirectory()) {
|
||||
// Recurse
|
||||
yield cpDirRecursive(srcFile, destFile, currentDepth, force);
|
||||
}
|
||||
else {
|
||||
yield copyFile(srcFile, destFile, force);
|
||||
}
|
||||
}
|
||||
// Change the mode for the newly created directory
|
||||
yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);
|
||||
});
|
||||
}
|
||||
// Buffered file copy
|
||||
function copyFile(srcFile, destFile, force) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {
|
||||
// unlink/re-link it
|
||||
try {
|
||||
yield ioUtil.lstat(destFile);
|
||||
yield ioUtil.unlink(destFile);
|
||||
}
|
||||
catch (e) {
|
||||
// Try to override file permission
|
||||
if (e.code === 'EPERM') {
|
||||
yield ioUtil.chmod(destFile, '0666');
|
||||
yield ioUtil.unlink(destFile);
|
||||
}
|
||||
// other errors = it doesn't exist, no work to do
|
||||
}
|
||||
// Copy over symlink
|
||||
const symlinkFull = yield ioUtil.readlink(srcFile);
|
||||
yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);
|
||||
}
|
||||
else if (!(yield ioUtil.exists(destFile)) || force) {
|
||||
yield ioUtil.copyFile(srcFile, destFile);
|
||||
}
|
||||
});
|
||||
}
|
||||
//# sourceMappingURL=io.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+37
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@actions/io",
|
||||
"version": "1.1.1",
|
||||
"description": "Actions io lib",
|
||||
"keywords": [
|
||||
"github",
|
||||
"actions",
|
||||
"io"
|
||||
],
|
||||
"homepage": "https://github.com/actions/toolkit/tree/main/packages/io",
|
||||
"license": "MIT",
|
||||
"main": "lib/io.js",
|
||||
"types": "lib/io.d.ts",
|
||||
"directories": {
|
||||
"lib": "lib",
|
||||
"test": "__tests__"
|
||||
},
|
||||
"files": [
|
||||
"lib"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/actions/toolkit.git",
|
||||
"directory": "packages/io"
|
||||
},
|
||||
"scripts": {
|
||||
"audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/actions/toolkit/issues"
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
# `@actions/tool-cache`
|
||||
|
||||
> Functions necessary for downloading and caching tools.
|
||||
|
||||
## Usage
|
||||
|
||||
#### Download
|
||||
|
||||
You can use this to download tools (or other files) from a download URL:
|
||||
|
||||
```js
|
||||
const tc = require('@actions/tool-cache');
|
||||
|
||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||
```
|
||||
|
||||
#### Extract
|
||||
|
||||
These can then be extracted in platform specific ways:
|
||||
|
||||
```js
|
||||
const tc = require('@actions/tool-cache');
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
const node12Path = tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip');
|
||||
const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to');
|
||||
|
||||
// Or alternately
|
||||
const node12Path = tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z');
|
||||
const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to');
|
||||
}
|
||||
else {
|
||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
||||
}
|
||||
```
|
||||
|
||||
#### Cache
|
||||
|
||||
Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for private runners (private runners are still in development but are on the roadmap).
|
||||
|
||||
You'll often want to add it to the path as part of this step:
|
||||
|
||||
```js
|
||||
const tc = require('@actions/tool-cache');
|
||||
const core = require('@actions/core');
|
||||
|
||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
||||
|
||||
const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0');
|
||||
core.addPath(cachedPath);
|
||||
```
|
||||
|
||||
You can also cache files for reuse.
|
||||
|
||||
```js
|
||||
const tc = require('@actions/tool-cache');
|
||||
|
||||
tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0');
|
||||
```
|
||||
|
||||
#### Find
|
||||
|
||||
Finally, you can find directories and files you've previously cached:
|
||||
|
||||
```js
|
||||
const tc = require('@actions/tool-cache');
|
||||
const core = require('@actions/core');
|
||||
|
||||
const nodeDirectory = tc.find('node', '12.x', 'x64');
|
||||
core.addPath(nodeDirectory);
|
||||
```
|
||||
|
||||
You can even find all cached versions of a tool:
|
||||
|
||||
```js
|
||||
const tc = require('@actions/tool-cache');
|
||||
|
||||
const allNodeVersions = tc.findAllVersions('node');
|
||||
console.log(`Versions of node available: ${allNodeVersions}`);
|
||||
```
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
export declare class HTTPError extends Error {
|
||||
readonly httpStatusCode: number | undefined;
|
||||
constructor(httpStatusCode: number | undefined);
|
||||
}
|
||||
/**
|
||||
* Download a tool from an url and stream it into a file
|
||||
*
|
||||
* @param url url of tool to download
|
||||
* @returns path to downloaded tool
|
||||
*/
|
||||
export declare function downloadTool(url: string): Promise<string>;
|
||||
/**
|
||||
* Extract a .7z file
|
||||
*
|
||||
* @param file path to the .7z file
|
||||
* @param dest destination directory. Optional.
|
||||
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
|
||||
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
|
||||
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
|
||||
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
|
||||
* interface, it is smaller than the full command line interface, and it does support long paths. At the
|
||||
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
|
||||
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
|
||||
* to 7zr.exe can be pass to this function.
|
||||
* @returns path to the destination directory
|
||||
*/
|
||||
export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>;
|
||||
/**
|
||||
* Extract a tar
|
||||
*
|
||||
* @param file path to the tar
|
||||
* @param dest destination directory. Optional.
|
||||
* @param flags flags for the tar. Optional.
|
||||
* @returns path to the destination directory
|
||||
*/
|
||||
export declare function extractTar(file: string, dest?: string, flags?: string): Promise<string>;
|
||||
/**
|
||||
* Extract a zip
|
||||
*
|
||||
* @param file path to the zip
|
||||
* @param dest destination directory. Optional.
|
||||
* @returns path to the destination directory
|
||||
*/
|
||||
export declare function extractZip(file: string, dest?: string): Promise<string>;
|
||||
/**
|
||||
* Caches a directory and installs it into the tool cacheDir
|
||||
*
|
||||
* @param sourceDir the directory to cache into tools
|
||||
* @param tool tool name
|
||||
* @param version version of the tool. semver format
|
||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
||||
*/
|
||||
export declare function cacheDir(sourceDir: string, tool: string, version: string, arch?: string): Promise<string>;
|
||||
/**
|
||||
* Caches a downloaded file (GUID) and installs it
|
||||
* into the tool cache with a given targetName
|
||||
*
|
||||
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
|
||||
* @param targetFile the name of the file name in the tools directory
|
||||
* @param tool tool name
|
||||
* @param version version of the tool. semver format
|
||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
||||
*/
|
||||
export declare function cacheFile(sourceFile: string, targetFile: string, tool: string, version: string, arch?: string): Promise<string>;
|
||||
/**
|
||||
* Finds the path to a tool version in the local installed tool cache
|
||||
*
|
||||
* @param toolName name of the tool
|
||||
* @param versionSpec version of the tool
|
||||
* @param arch optional arch. defaults to arch of computer
|
||||
*/
|
||||
export declare function find(toolName: string, versionSpec: string, arch?: string): string;
|
||||
/**
|
||||
* Finds the paths to all versions of a tool that are installed in the local tool cache
|
||||
*
|
||||
* @param toolName name of the tool
|
||||
* @param arch optional arch. defaults to arch of computer
|
||||
*/
|
||||
export declare function findAllVersions(toolName: string, arch?: string): string[];
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const core = require("@actions/core");
|
||||
const io = require("@actions/io");
|
||||
const fs = require("fs");
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const httpm = require("typed-rest-client/HttpClient");
|
||||
const semver = require("semver");
|
||||
const uuidV4 = require("uuid/v4");
|
||||
const exec_1 = require("@actions/exec/lib/exec");
|
||||
const assert_1 = require("assert");
|
||||
class HTTPError extends Error {
|
||||
constructor(httpStatusCode) {
|
||||
super(`Unexpected HTTP response: ${httpStatusCode}`);
|
||||
this.httpStatusCode = httpStatusCode;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
exports.HTTPError = HTTPError;
|
||||
const IS_WINDOWS = process.platform === 'win32';
|
||||
const userAgent = 'actions/tool-cache';
|
||||
// On load grab temp directory and cache directory and remove them from env (currently don't want to expose this)
|
||||
let tempDirectory = process.env['RUNNER_TEMP'] || '';
|
||||
let cacheRoot = process.env['RUNNER_TOOL_CACHE'] || '';
|
||||
// If directories not found, place them in common temp locations
|
||||
if (!tempDirectory || !cacheRoot) {
|
||||
let baseLocation;
|
||||
if (IS_WINDOWS) {
|
||||
// On windows use the USERPROFILE env variable
|
||||
baseLocation = process.env['USERPROFILE'] || 'C:\\';
|
||||
}
|
||||
else {
|
||||
if (process.platform === 'darwin') {
|
||||
baseLocation = '/Users';
|
||||
}
|
||||
else {
|
||||
baseLocation = '/home';
|
||||
}
|
||||
}
|
||||
if (!tempDirectory) {
|
||||
tempDirectory = path.join(baseLocation, 'actions', 'temp');
|
||||
}
|
||||
if (!cacheRoot) {
|
||||
cacheRoot = path.join(baseLocation, 'actions', 'cache');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Download a tool from an url and stream it into a file
|
||||
*
|
||||
* @param url url of tool to download
|
||||
* @returns path to downloaded tool
|
||||
*/
|
||||
function downloadTool(url) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
// Wrap in a promise so that we can resolve from within stream callbacks
|
||||
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const http = new httpm.HttpClient(userAgent, [], {
|
||||
allowRetries: true,
|
||||
maxRetries: 3
|
||||
});
|
||||
const destPath = path.join(tempDirectory, uuidV4());
|
||||
yield io.mkdirP(tempDirectory);
|
||||
core.debug(`Downloading ${url}`);
|
||||
core.debug(`Downloading ${destPath}`);
|
||||
if (fs.existsSync(destPath)) {
|
||||
throw new Error(`Destination file path ${destPath} already exists`);
|
||||
}
|
||||
const response = yield http.get(url);
|
||||
if (response.message.statusCode !== 200) {
|
||||
const err = new HTTPError(response.message.statusCode);
|
||||
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
||||
throw err;
|
||||
}
|
||||
const file = fs.createWriteStream(destPath);
|
||||
file.on('open', () => __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const stream = response.message.pipe(file);
|
||||
stream.on('close', () => {
|
||||
core.debug('download complete');
|
||||
resolve(destPath);
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
||||
reject(err);
|
||||
}
|
||||
}));
|
||||
file.on('error', err => {
|
||||
file.end();
|
||||
reject(err);
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
exports.downloadTool = downloadTool;
|
||||
/**
|
||||
* Extract a .7z file
|
||||
*
|
||||
* @param file path to the .7z file
|
||||
* @param dest destination directory. Optional.
|
||||
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
|
||||
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
|
||||
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
|
||||
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
|
||||
* interface, it is smaller than the full command line interface, and it does support long paths. At the
|
||||
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
|
||||
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
|
||||
* to 7zr.exe can be pass to this function.
|
||||
* @returns path to the destination directory
|
||||
*/
|
||||
function extract7z(file, dest, _7zPath) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS');
|
||||
assert_1.ok(file, 'parameter "file" is required');
|
||||
dest = dest || (yield _createExtractFolder(dest));
|
||||
const originalCwd = process.cwd();
|
||||
process.chdir(dest);
|
||||
if (_7zPath) {
|
||||
try {
|
||||
const args = [
|
||||
'x',
|
||||
'-bb1',
|
||||
'-bd',
|
||||
'-sccUTF-8',
|
||||
file
|
||||
];
|
||||
const options = {
|
||||
silent: true
|
||||
};
|
||||
yield exec_1.exec(`"${_7zPath}"`, args, options);
|
||||
}
|
||||
finally {
|
||||
process.chdir(originalCwd);
|
||||
}
|
||||
}
|
||||
else {
|
||||
const escapedScript = path
|
||||
.join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1')
|
||||
.replace(/'/g, "''")
|
||||
.replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
|
||||
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
||||
const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
||||
const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
|
||||
const args = [
|
||||
'-NoLogo',
|
||||
'-Sta',
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-ExecutionPolicy',
|
||||
'Unrestricted',
|
||||
'-Command',
|
||||
command
|
||||
];
|
||||
const options = {
|
||||
silent: true
|
||||
};
|
||||
try {
|
||||
const powershellPath = yield io.which('powershell', true);
|
||||
yield exec_1.exec(`"${powershellPath}"`, args, options);
|
||||
}
|
||||
finally {
|
||||
process.chdir(originalCwd);
|
||||
}
|
||||
}
|
||||
return dest;
|
||||
});
|
||||
}
|
||||
exports.extract7z = extract7z;
|
||||
/**
|
||||
* Extract a tar
|
||||
*
|
||||
* @param file path to the tar
|
||||
* @param dest destination directory. Optional.
|
||||
* @param flags flags for the tar. Optional.
|
||||
* @returns path to the destination directory
|
||||
*/
|
||||
function extractTar(file, dest, flags = 'xz') {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!file) {
|
||||
throw new Error("parameter 'file' is required");
|
||||
}
|
||||
dest = dest || (yield _createExtractFolder(dest));
|
||||
const tarPath = yield io.which('tar', true);
|
||||
yield exec_1.exec(`"${tarPath}"`, [flags, '-C', dest, '-f', file]);
|
||||
return dest;
|
||||
});
|
||||
}
|
||||
exports.extractTar = extractTar;
|
||||
/**
|
||||
* Extract a zip
|
||||
*
|
||||
* @param file path to the zip
|
||||
* @param dest destination directory. Optional.
|
||||
* @returns path to the destination directory
|
||||
*/
|
||||
function extractZip(file, dest) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!file) {
|
||||
throw new Error("parameter 'file' is required");
|
||||
}
|
||||
dest = dest || (yield _createExtractFolder(dest));
|
||||
if (IS_WINDOWS) {
|
||||
yield extractZipWin(file, dest);
|
||||
}
|
||||
else {
|
||||
yield extractZipNix(file, dest);
|
||||
}
|
||||
return dest;
|
||||
});
|
||||
}
|
||||
exports.extractZip = extractZip;
|
||||
function extractZipWin(file, dest) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
// build the powershell command
|
||||
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
|
||||
const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
||||
const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`;
|
||||
// run powershell
|
||||
const powershellPath = yield io.which('powershell');
|
||||
const args = [
|
||||
'-NoLogo',
|
||||
'-Sta',
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-ExecutionPolicy',
|
||||
'Unrestricted',
|
||||
'-Command',
|
||||
command
|
||||
];
|
||||
yield exec_1.exec(`"${powershellPath}"`, args);
|
||||
});
|
||||
}
|
||||
function extractZipNix(file, dest) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const unzipPath = yield io.which('unzip');
|
||||
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest });
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Caches a directory and installs it into the tool cacheDir
|
||||
*
|
||||
* @param sourceDir the directory to cache into tools
|
||||
* @param tool tool name
|
||||
* @param version version of the tool. semver format
|
||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
||||
*/
|
||||
function cacheDir(sourceDir, tool, version, arch) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
version = semver.clean(version) || version;
|
||||
arch = arch || os.arch();
|
||||
core.debug(`Caching tool ${tool} ${version} ${arch}`);
|
||||
core.debug(`source dir: ${sourceDir}`);
|
||||
if (!fs.statSync(sourceDir).isDirectory()) {
|
||||
throw new Error('sourceDir is not a directory');
|
||||
}
|
||||
// Create the tool dir
|
||||
const destPath = yield _createToolPath(tool, version, arch);
|
||||
// copy each child item. do not move. move can fail on Windows
|
||||
// due to anti-virus software having an open handle on a file.
|
||||
for (const itemName of fs.readdirSync(sourceDir)) {
|
||||
const s = path.join(sourceDir, itemName);
|
||||
yield io.cp(s, destPath, { recursive: true });
|
||||
}
|
||||
// write .complete
|
||||
_completeToolPath(tool, version, arch);
|
||||
return destPath;
|
||||
});
|
||||
}
|
||||
exports.cacheDir = cacheDir;
|
||||
/**
|
||||
* Caches a downloaded file (GUID) and installs it
|
||||
* into the tool cache with a given targetName
|
||||
*
|
||||
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
|
||||
* @param targetFile the name of the file name in the tools directory
|
||||
* @param tool tool name
|
||||
* @param version version of the tool. semver format
|
||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
||||
*/
|
||||
function cacheFile(sourceFile, targetFile, tool, version, arch) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
version = semver.clean(version) || version;
|
||||
arch = arch || os.arch();
|
||||
core.debug(`Caching tool ${tool} ${version} ${arch}`);
|
||||
core.debug(`source file: ${sourceFile}`);
|
||||
if (!fs.statSync(sourceFile).isFile()) {
|
||||
throw new Error('sourceFile is not a file');
|
||||
}
|
||||
// create the tool dir
|
||||
const destFolder = yield _createToolPath(tool, version, arch);
|
||||
// copy instead of move. move can fail on Windows due to
|
||||
// anti-virus software having an open handle on a file.
|
||||
const destPath = path.join(destFolder, targetFile);
|
||||
core.debug(`destination file ${destPath}`);
|
||||
yield io.cp(sourceFile, destPath);
|
||||
// write .complete
|
||||
_completeToolPath(tool, version, arch);
|
||||
return destFolder;
|
||||
});
|
||||
}
|
||||
exports.cacheFile = cacheFile;
|
||||
/**
|
||||
* Finds the path to a tool version in the local installed tool cache
|
||||
*
|
||||
* @param toolName name of the tool
|
||||
* @param versionSpec version of the tool
|
||||
* @param arch optional arch. defaults to arch of computer
|
||||
*/
|
||||
function find(toolName, versionSpec, arch) {
|
||||
if (!toolName) {
|
||||
throw new Error('toolName parameter is required');
|
||||
}
|
||||
if (!versionSpec) {
|
||||
throw new Error('versionSpec parameter is required');
|
||||
}
|
||||
arch = arch || os.arch();
|
||||
// attempt to resolve an explicit version
|
||||
if (!_isExplicitVersion(versionSpec)) {
|
||||
const localVersions = findAllVersions(toolName, arch);
|
||||
const match = _evaluateVersions(localVersions, versionSpec);
|
||||
versionSpec = match;
|
||||
}
|
||||
// check for the explicit version in the cache
|
||||
let toolPath = '';
|
||||
if (versionSpec) {
|
||||
versionSpec = semver.clean(versionSpec) || '';
|
||||
const cachePath = path.join(cacheRoot, toolName, versionSpec, arch);
|
||||
core.debug(`checking cache: ${cachePath}`);
|
||||
if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) {
|
||||
core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
|
||||
toolPath = cachePath;
|
||||
}
|
||||
else {
|
||||
core.debug('not found');
|
||||
}
|
||||
}
|
||||
return toolPath;
|
||||
}
|
||||
exports.find = find;
|
||||
/**
|
||||
* Finds the paths to all versions of a tool that are installed in the local tool cache
|
||||
*
|
||||
* @param toolName name of the tool
|
||||
* @param arch optional arch. defaults to arch of computer
|
||||
*/
|
||||
function findAllVersions(toolName, arch) {
|
||||
const versions = [];
|
||||
arch = arch || os.arch();
|
||||
const toolPath = path.join(cacheRoot, toolName);
|
||||
if (fs.existsSync(toolPath)) {
|
||||
const children = fs.readdirSync(toolPath);
|
||||
for (const child of children) {
|
||||
if (_isExplicitVersion(child)) {
|
||||
const fullPath = path.join(toolPath, child, arch || '');
|
||||
if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) {
|
||||
versions.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return versions;
|
||||
}
|
||||
exports.findAllVersions = findAllVersions;
|
||||
function _createExtractFolder(dest) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!dest) {
|
||||
// create a temp dir
|
||||
dest = path.join(tempDirectory, uuidV4());
|
||||
}
|
||||
yield io.mkdirP(dest);
|
||||
return dest;
|
||||
});
|
||||
}
|
||||
function _createToolPath(tool, version, arch) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
||||
core.debug(`destination ${folderPath}`);
|
||||
const markerPath = `${folderPath}.complete`;
|
||||
yield io.rmRF(folderPath);
|
||||
yield io.rmRF(markerPath);
|
||||
yield io.mkdirP(folderPath);
|
||||
return folderPath;
|
||||
});
|
||||
}
|
||||
function _completeToolPath(tool, version, arch) {
|
||||
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
||||
const markerPath = `${folderPath}.complete`;
|
||||
fs.writeFileSync(markerPath, '');
|
||||
core.debug('finished caching tool');
|
||||
}
|
||||
function _isExplicitVersion(versionSpec) {
|
||||
const c = semver.clean(versionSpec) || '';
|
||||
core.debug(`isExplicit: ${c}`);
|
||||
const valid = semver.valid(c) != null;
|
||||
core.debug(`explicit? ${valid}`);
|
||||
return valid;
|
||||
}
|
||||
function _evaluateVersions(versions, versionSpec) {
|
||||
let version = '';
|
||||
core.debug(`evaluating ${versions.length} versions`);
|
||||
versions = versions.sort((a, b) => {
|
||||
if (semver.gt(a, b)) {
|
||||
return 1;
|
||||
}
|
||||
return -1;
|
||||
});
|
||||
for (let i = versions.length - 1; i >= 0; i--) {
|
||||
const potential = versions[i];
|
||||
const satisfied = semver.satisfies(potential, versionSpec);
|
||||
if (satisfied) {
|
||||
version = potential;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (version) {
|
||||
core.debug(`matched: ${version}`);
|
||||
}
|
||||
else {
|
||||
core.debug('match not found');
|
||||
}
|
||||
return version;
|
||||
}
|
||||
//# sourceMappingURL=tool-cache.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+49
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "@actions/tool-cache",
|
||||
"version": "1.1.2",
|
||||
"description": "Actions tool-cache lib",
|
||||
"keywords": [
|
||||
"github",
|
||||
"actions",
|
||||
"exec"
|
||||
],
|
||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
|
||||
"license": "MIT",
|
||||
"main": "lib/tool-cache.js",
|
||||
"directories": {
|
||||
"lib": "lib",
|
||||
"test": "__tests__"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"scripts"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/actions/toolkit.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
||||
"tsc": "tsc"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/actions/toolkit/issues"
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.1.0",
|
||||
"@actions/exec": "^1.0.1",
|
||||
"@actions/io": "^1.0.1",
|
||||
"semver": "^6.1.0",
|
||||
"typed-rest-client": "^1.4.0",
|
||||
"uuid": "^3.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/nock": "^10.0.3",
|
||||
"@types/semver": "^6.0.0",
|
||||
"@types/uuid": "^3.4.4",
|
||||
"nock": "^10.0.6"
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Source,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Target)
|
||||
|
||||
# This script translates the output from 7zdec into UTF8. Node has limited
|
||||
# built-in support for encodings.
|
||||
#
|
||||
# 7zdec uses the system default code page. The system default code page varies
|
||||
# depending on the locale configuration. On an en-US box, the system default code
|
||||
# page is Windows-1252.
|
||||
#
|
||||
# Note, on a typical en-US box, testing with the 'ç' character is a good way to
|
||||
# determine whether data is passed correctly between processes. This is because
|
||||
# the 'ç' character has a different code point across each of the common encodings
|
||||
# on a typical en-US box, i.e.
|
||||
# 1) the default console-output code page (IBM437)
|
||||
# 2) the system default code page (i.e. CP_ACP) (Windows-1252)
|
||||
# 3) UTF8
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Redefine the wrapper over STDOUT to use UTF8. Node expects UTF8 by default.
|
||||
$stdout = [System.Console]::OpenStandardOutput()
|
||||
$utf8 = New-Object System.Text.UTF8Encoding($false) # do not emit BOM
|
||||
$writer = New-Object System.IO.StreamWriter($stdout, $utf8)
|
||||
[System.Console]::SetOut($writer)
|
||||
|
||||
# All subsequent output must be written using [System.Console]::WriteLine(). In
|
||||
# PowerShell 4, Write-Host and Out-Default do not consider the updated stream writer.
|
||||
|
||||
Set-Location -LiteralPath $Target
|
||||
|
||||
# Print the ##command.
|
||||
$_7zdec = Join-Path -Path "$PSScriptRoot" -ChildPath "externals/7zdec.exe"
|
||||
[System.Console]::WriteLine("##[command]$_7zdec x `"$Source`"")
|
||||
|
||||
# The $OutputEncoding variable instructs PowerShell how to interpret the output
|
||||
# from the external command.
|
||||
$OutputEncoding = [System.Text.Encoding]::Default
|
||||
|
||||
# Note, the output from 7zdec.exe needs to be iterated over. Otherwise PowerShell.exe
|
||||
# will launch the external command in such a way that it inherits the streams.
|
||||
& $_7zdec x $Source 2>&1 |
|
||||
ForEach-Object {
|
||||
if ($_ -is [System.Management.Automation.ErrorRecord]) {
|
||||
[System.Console]::WriteLine($_.Exception.Message)
|
||||
}
|
||||
else {
|
||||
[System.Console]::WriteLine($_)
|
||||
}
|
||||
}
|
||||
[System.Console]::WriteLine("##[debug]7zdec.exe exit code '$LASTEXITCODE'")
|
||||
[System.Console]::Out.Flush()
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
BIN
Binary file not shown.
+22
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014-present Sebastian McKenzie and other contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# @babel/code-frame
|
||||
|
||||
> Generate errors that contain a code frame that point to source locations.
|
||||
|
||||
See our website [@babel/code-frame](https://babeljs.io/docs/en/babel-code-frame) for more information.
|
||||
|
||||
## Install
|
||||
|
||||
Using npm:
|
||||
|
||||
```sh
|
||||
npm install --save-dev @babel/code-frame
|
||||
```
|
||||
|
||||
or using yarn:
|
||||
|
||||
```sh
|
||||
yarn add @babel/code-frame --dev
|
||||
```
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.codeFrameColumns = codeFrameColumns;
|
||||
exports.default = _default;
|
||||
|
||||
var _highlight = require("@babel/highlight");
|
||||
|
||||
let deprecationWarningShown = false;
|
||||
|
||||
function getDefs(chalk) {
|
||||
return {
|
||||
gutter: chalk.grey,
|
||||
marker: chalk.red.bold,
|
||||
message: chalk.red.bold
|
||||
};
|
||||
}
|
||||
|
||||
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
|
||||
|
||||
function getMarkerLines(loc, source, opts) {
|
||||
const startLoc = Object.assign({
|
||||
column: 0,
|
||||
line: -1
|
||||
}, loc.start);
|
||||
const endLoc = Object.assign({}, startLoc, loc.end);
|
||||
const {
|
||||
linesAbove = 2,
|
||||
linesBelow = 3
|
||||
} = opts || {};
|
||||
const startLine = startLoc.line;
|
||||
const startColumn = startLoc.column;
|
||||
const endLine = endLoc.line;
|
||||
const endColumn = endLoc.column;
|
||||
let start = Math.max(startLine - (linesAbove + 1), 0);
|
||||
let end = Math.min(source.length, endLine + linesBelow);
|
||||
|
||||
if (startLine === -1) {
|
||||
start = 0;
|
||||
}
|
||||
|
||||
if (endLine === -1) {
|
||||
end = source.length;
|
||||
}
|
||||
|
||||
const lineDiff = endLine - startLine;
|
||||
const markerLines = {};
|
||||
|
||||
if (lineDiff) {
|
||||
for (let i = 0; i <= lineDiff; i++) {
|
||||
const lineNumber = i + startLine;
|
||||
|
||||
if (!startColumn) {
|
||||
markerLines[lineNumber] = true;
|
||||
} else if (i === 0) {
|
||||
const sourceLength = source[lineNumber - 1].length;
|
||||
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
|
||||
} else if (i === lineDiff) {
|
||||
markerLines[lineNumber] = [0, endColumn];
|
||||
} else {
|
||||
const sourceLength = source[lineNumber - i].length;
|
||||
markerLines[lineNumber] = [0, sourceLength];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (startColumn === endColumn) {
|
||||
if (startColumn) {
|
||||
markerLines[startLine] = [startColumn, 0];
|
||||
} else {
|
||||
markerLines[startLine] = true;
|
||||
}
|
||||
} else {
|
||||
markerLines[startLine] = [startColumn, endColumn - startColumn];
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
start,
|
||||
end,
|
||||
markerLines
|
||||
};
|
||||
}
|
||||
|
||||
function codeFrameColumns(rawLines, loc, opts = {}) {
|
||||
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
|
||||
const chalk = (0, _highlight.getChalk)(opts);
|
||||
const defs = getDefs(chalk);
|
||||
|
||||
const maybeHighlight = (chalkFn, string) => {
|
||||
return highlighted ? chalkFn(string) : string;
|
||||
};
|
||||
|
||||
const lines = rawLines.split(NEWLINE);
|
||||
const {
|
||||
start,
|
||||
end,
|
||||
markerLines
|
||||
} = getMarkerLines(loc, lines, opts);
|
||||
const hasColumns = loc.start && typeof loc.start.column === "number";
|
||||
const numberMaxWidth = String(end).length;
|
||||
const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
|
||||
let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
|
||||
const number = start + 1 + index;
|
||||
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
|
||||
const gutter = ` ${paddedNumber} |`;
|
||||
const hasMarker = markerLines[number];
|
||||
const lastMarkerLine = !markerLines[number + 1];
|
||||
|
||||
if (hasMarker) {
|
||||
let markerLine = "";
|
||||
|
||||
if (Array.isArray(hasMarker)) {
|
||||
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
|
||||
const numberOfMarkers = hasMarker[1] || 1;
|
||||
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
|
||||
|
||||
if (lastMarkerLine && opts.message) {
|
||||
markerLine += " " + maybeHighlight(defs.message, opts.message);
|
||||
}
|
||||
}
|
||||
|
||||
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
|
||||
} else {
|
||||
return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`;
|
||||
}
|
||||
}).join("\n");
|
||||
|
||||
if (opts.message && !hasColumns) {
|
||||
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
|
||||
}
|
||||
|
||||
if (highlighted) {
|
||||
return chalk.reset(frame);
|
||||
} else {
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
|
||||
function _default(rawLines, lineNumber, colNumber, opts = {}) {
|
||||
if (!deprecationWarningShown) {
|
||||
deprecationWarningShown = true;
|
||||
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
|
||||
|
||||
if (process.emitWarning) {
|
||||
process.emitWarning(message, "DeprecationWarning");
|
||||
} else {
|
||||
const deprecationError = new Error(message);
|
||||
deprecationError.name = "DeprecationWarning";
|
||||
console.warn(new Error(message));
|
||||
}
|
||||
}
|
||||
|
||||
colNumber = Math.max(colNumber, 0);
|
||||
const location = {
|
||||
start: {
|
||||
column: colNumber,
|
||||
line: lineNumber
|
||||
}
|
||||
};
|
||||
return codeFrameColumns(rawLines, location, opts);
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@babel/code-frame",
|
||||
"version": "7.14.5",
|
||||
"description": "Generate errors that contain a code frame that point to source locations.",
|
||||
"author": "The Babel Team (https://babel.dev/team)",
|
||||
"homepage": "https://babel.dev/docs/en/next/babel-code-frame",
|
||||
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen",
|
||||
"license": "MIT",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/babel/babel.git",
|
||||
"directory": "packages/babel-code-frame"
|
||||
},
|
||||
"main": "./lib/index.js",
|
||||
"dependencies": {
|
||||
"@babel/highlight": "^7.14.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/chalk": "^2.0.0",
|
||||
"chalk": "^2.0.0",
|
||||
"strip-ansi": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014-present Sebastian McKenzie and other contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./data/corejs2-built-ins.json");
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./data/corejs3-shipped-proposals.json");
|
||||
+1695
File diff suppressed because it is too large
Load Diff
+5
@@ -0,0 +1,5 @@
|
||||
[
|
||||
"esnext.global-this",
|
||||
"esnext.promise.all-settled",
|
||||
"esnext.string.match-all"
|
||||
]
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"es6.module": {
|
||||
"chrome": "61",
|
||||
"and_chr": "61",
|
||||
"edge": "16",
|
||||
"firefox": "60",
|
||||
"and_ff": "60",
|
||||
"node": "13.2.0",
|
||||
"opera": "48",
|
||||
"op_mob": "48",
|
||||
"safari": "10.1",
|
||||
"ios": "10.3",
|
||||
"samsung": "8.2",
|
||||
"android": "61",
|
||||
"electron": "2.0",
|
||||
"ios_saf": "10.3"
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"transform-async-to-generator": [
|
||||
"bugfix/transform-async-arrows-in-class"
|
||||
],
|
||||
"transform-parameters": [
|
||||
"bugfix/transform-edge-default-parameters"
|
||||
],
|
||||
"transform-function-name": [
|
||||
"bugfix/transform-edge-function-name"
|
||||
],
|
||||
"transform-block-scoping": [
|
||||
"bugfix/transform-safari-block-shadowing",
|
||||
"bugfix/transform-safari-for-shadowing"
|
||||
],
|
||||
"transform-template-literals": [
|
||||
"bugfix/transform-tagged-template-caching"
|
||||
],
|
||||
"proposal-optional-chaining": [
|
||||
"bugfix/transform-v8-spread-parameters-in-optional-chaining"
|
||||
]
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
{
|
||||
"transform-async-to-generator": {
|
||||
"chrome": "55",
|
||||
"opera": "42",
|
||||
"edge": "15",
|
||||
"firefox": "52",
|
||||
"safari": "10.1",
|
||||
"node": "7.6",
|
||||
"ios": "10.3",
|
||||
"samsung": "6",
|
||||
"electron": "1.6"
|
||||
},
|
||||
"bugfix/transform-async-arrows-in-class": {
|
||||
"chrome": "55",
|
||||
"opera": "42",
|
||||
"edge": "15",
|
||||
"firefox": "52",
|
||||
"safari": "11",
|
||||
"node": "7.6",
|
||||
"ios": "11",
|
||||
"samsung": "6",
|
||||
"electron": "1.6"
|
||||
},
|
||||
"transform-parameters": {
|
||||
"chrome": "49",
|
||||
"opera": "36",
|
||||
"edge": "15",
|
||||
"firefox": "53",
|
||||
"safari": "10",
|
||||
"node": "6",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.37"
|
||||
},
|
||||
"bugfix/transform-edge-default-parameters": {
|
||||
"chrome": "49",
|
||||
"opera": "36",
|
||||
"edge": "18",
|
||||
"firefox": "52",
|
||||
"safari": "10",
|
||||
"node": "6",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.37"
|
||||
},
|
||||
"transform-function-name": {
|
||||
"chrome": "51",
|
||||
"opera": "38",
|
||||
"edge": "14",
|
||||
"firefox": "53",
|
||||
"safari": "10",
|
||||
"node": "6.5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "1.2"
|
||||
},
|
||||
"bugfix/transform-edge-function-name": {
|
||||
"chrome": "51",
|
||||
"opera": "38",
|
||||
"edge": "79",
|
||||
"firefox": "53",
|
||||
"safari": "10",
|
||||
"node": "6.5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "1.2"
|
||||
},
|
||||
"transform-block-scoping": {
|
||||
"chrome": "49",
|
||||
"opera": "36",
|
||||
"edge": "14",
|
||||
"firefox": "51",
|
||||
"safari": "10",
|
||||
"node": "6",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.37"
|
||||
},
|
||||
"bugfix/transform-safari-block-shadowing": {
|
||||
"chrome": "49",
|
||||
"opera": "36",
|
||||
"edge": "12",
|
||||
"firefox": "44",
|
||||
"safari": "11",
|
||||
"node": "6",
|
||||
"ie": "11",
|
||||
"ios": "11",
|
||||
"samsung": "5",
|
||||
"electron": "0.37"
|
||||
},
|
||||
"bugfix/transform-safari-for-shadowing": {
|
||||
"chrome": "49",
|
||||
"opera": "36",
|
||||
"edge": "12",
|
||||
"firefox": "4",
|
||||
"safari": "11",
|
||||
"node": "6",
|
||||
"ie": "11",
|
||||
"ios": "11",
|
||||
"samsung": "5",
|
||||
"electron": "0.37"
|
||||
},
|
||||
"transform-template-literals": {
|
||||
"chrome": "41",
|
||||
"opera": "28",
|
||||
"edge": "13",
|
||||
"firefox": "34",
|
||||
"safari": "9",
|
||||
"node": "4",
|
||||
"ios": "9",
|
||||
"samsung": "3.4",
|
||||
"electron": "0.21"
|
||||
},
|
||||
"bugfix/transform-tagged-template-caching": {
|
||||
"chrome": "41",
|
||||
"opera": "28",
|
||||
"edge": "12",
|
||||
"firefox": "34",
|
||||
"safari": "13",
|
||||
"node": "4",
|
||||
"ios": "13",
|
||||
"samsung": "3.4",
|
||||
"electron": "0.21"
|
||||
},
|
||||
"proposal-optional-chaining": {
|
||||
"chrome": "80",
|
||||
"opera": "67",
|
||||
"edge": "80",
|
||||
"firefox": "74",
|
||||
"safari": "13.1",
|
||||
"node": "14",
|
||||
"ios": "13.4",
|
||||
"samsung": "13",
|
||||
"electron": "8.0"
|
||||
},
|
||||
"bugfix/transform-v8-spread-parameters-in-optional-chaining": {
|
||||
"firefox": "74",
|
||||
"safari": "13.1",
|
||||
"ios": "13.4"
|
||||
}
|
||||
}
|
||||
+453
@@ -0,0 +1,453 @@
|
||||
{
|
||||
"proposal-class-static-block": {
|
||||
"chrome": "91",
|
||||
"electron": "13.0"
|
||||
},
|
||||
"proposal-private-property-in-object": {
|
||||
"chrome": "91",
|
||||
"firefox": "90",
|
||||
"electron": "13.0"
|
||||
},
|
||||
"proposal-class-properties": {
|
||||
"chrome": "74",
|
||||
"opera": "62",
|
||||
"edge": "79",
|
||||
"firefox": "90",
|
||||
"safari": "14.1",
|
||||
"node": "12",
|
||||
"samsung": "11",
|
||||
"electron": "6.0"
|
||||
},
|
||||
"proposal-private-methods": {
|
||||
"chrome": "84",
|
||||
"opera": "70",
|
||||
"edge": "84",
|
||||
"firefox": "90",
|
||||
"safari": "15",
|
||||
"node": "14.6",
|
||||
"electron": "10.0"
|
||||
},
|
||||
"proposal-numeric-separator": {
|
||||
"chrome": "75",
|
||||
"opera": "62",
|
||||
"edge": "79",
|
||||
"firefox": "70",
|
||||
"safari": "13",
|
||||
"node": "12.5",
|
||||
"ios": "13",
|
||||
"samsung": "11",
|
||||
"electron": "6.0"
|
||||
},
|
||||
"proposal-logical-assignment-operators": {
|
||||
"chrome": "85",
|
||||
"opera": "71",
|
||||
"edge": "85",
|
||||
"firefox": "79",
|
||||
"safari": "14",
|
||||
"node": "15",
|
||||
"ios": "14",
|
||||
"electron": "10.0"
|
||||
},
|
||||
"proposal-nullish-coalescing-operator": {
|
||||
"chrome": "80",
|
||||
"opera": "67",
|
||||
"edge": "80",
|
||||
"firefox": "72",
|
||||
"safari": "13.1",
|
||||
"node": "14",
|
||||
"ios": "13.4",
|
||||
"samsung": "13",
|
||||
"electron": "8.0"
|
||||
},
|
||||
"proposal-optional-chaining": {
|
||||
"firefox": "74",
|
||||
"safari": "13.1",
|
||||
"ios": "13.4"
|
||||
},
|
||||
"proposal-json-strings": {
|
||||
"chrome": "66",
|
||||
"opera": "53",
|
||||
"edge": "79",
|
||||
"firefox": "62",
|
||||
"safari": "12",
|
||||
"node": "10",
|
||||
"ios": "12",
|
||||
"samsung": "9",
|
||||
"electron": "3.0"
|
||||
},
|
||||
"proposal-optional-catch-binding": {
|
||||
"chrome": "66",
|
||||
"opera": "53",
|
||||
"edge": "79",
|
||||
"firefox": "58",
|
||||
"safari": "11.1",
|
||||
"node": "10",
|
||||
"ios": "11.3",
|
||||
"samsung": "9",
|
||||
"electron": "3.0"
|
||||
},
|
||||
"transform-parameters": {
|
||||
"chrome": "49",
|
||||
"opera": "36",
|
||||
"edge": "18",
|
||||
"firefox": "53",
|
||||
"safari": "10",
|
||||
"node": "6",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.37"
|
||||
},
|
||||
"proposal-async-generator-functions": {
|
||||
"chrome": "63",
|
||||
"opera": "50",
|
||||
"edge": "79",
|
||||
"firefox": "57",
|
||||
"safari": "12",
|
||||
"node": "10",
|
||||
"ios": "12",
|
||||
"samsung": "8",
|
||||
"electron": "3.0"
|
||||
},
|
||||
"proposal-object-rest-spread": {
|
||||
"chrome": "60",
|
||||
"opera": "47",
|
||||
"edge": "79",
|
||||
"firefox": "55",
|
||||
"safari": "11.1",
|
||||
"node": "8.3",
|
||||
"ios": "11.3",
|
||||
"samsung": "8",
|
||||
"electron": "2.0"
|
||||
},
|
||||
"transform-dotall-regex": {
|
||||
"chrome": "62",
|
||||
"opera": "49",
|
||||
"edge": "79",
|
||||
"firefox": "78",
|
||||
"safari": "11.1",
|
||||
"node": "8.10",
|
||||
"ios": "11.3",
|
||||
"samsung": "8",
|
||||
"electron": "3.0"
|
||||
},
|
||||
"proposal-unicode-property-regex": {
|
||||
"chrome": "64",
|
||||
"opera": "51",
|
||||
"edge": "79",
|
||||
"firefox": "78",
|
||||
"safari": "11.1",
|
||||
"node": "10",
|
||||
"ios": "11.3",
|
||||
"samsung": "9",
|
||||
"electron": "3.0"
|
||||
},
|
||||
"transform-named-capturing-groups-regex": {
|
||||
"chrome": "64",
|
||||
"opera": "51",
|
||||
"edge": "79",
|
||||
"firefox": "78",
|
||||
"safari": "11.1",
|
||||
"node": "10",
|
||||
"ios": "11.3",
|
||||
"samsung": "9",
|
||||
"electron": "3.0"
|
||||
},
|
||||
"transform-async-to-generator": {
|
||||
"chrome": "55",
|
||||
"opera": "42",
|
||||
"edge": "15",
|
||||
"firefox": "52",
|
||||
"safari": "11",
|
||||
"node": "7.6",
|
||||
"ios": "11",
|
||||
"samsung": "6",
|
||||
"electron": "1.6"
|
||||
},
|
||||
"transform-exponentiation-operator": {
|
||||
"chrome": "52",
|
||||
"opera": "39",
|
||||
"edge": "14",
|
||||
"firefox": "52",
|
||||
"safari": "10.1",
|
||||
"node": "7",
|
||||
"ios": "10.3",
|
||||
"samsung": "6",
|
||||
"electron": "1.3"
|
||||
},
|
||||
"transform-template-literals": {
|
||||
"chrome": "41",
|
||||
"opera": "28",
|
||||
"edge": "13",
|
||||
"firefox": "34",
|
||||
"safari": "13",
|
||||
"node": "4",
|
||||
"ios": "13",
|
||||
"samsung": "3.4",
|
||||
"electron": "0.21"
|
||||
},
|
||||
"transform-literals": {
|
||||
"chrome": "44",
|
||||
"opera": "31",
|
||||
"edge": "12",
|
||||
"firefox": "53",
|
||||
"safari": "9",
|
||||
"node": "4",
|
||||
"ios": "9",
|
||||
"samsung": "4",
|
||||
"electron": "0.30"
|
||||
},
|
||||
"transform-function-name": {
|
||||
"chrome": "51",
|
||||
"opera": "38",
|
||||
"edge": "79",
|
||||
"firefox": "53",
|
||||
"safari": "10",
|
||||
"node": "6.5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "1.2"
|
||||
},
|
||||
"transform-arrow-functions": {
|
||||
"chrome": "47",
|
||||
"opera": "34",
|
||||
"edge": "13",
|
||||
"firefox": "45",
|
||||
"safari": "10",
|
||||
"node": "6",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.36"
|
||||
},
|
||||
"transform-block-scoped-functions": {
|
||||
"chrome": "41",
|
||||
"opera": "28",
|
||||
"edge": "12",
|
||||
"firefox": "46",
|
||||
"safari": "10",
|
||||
"node": "4",
|
||||
"ie": "11",
|
||||
"ios": "10",
|
||||
"samsung": "3.4",
|
||||
"electron": "0.21"
|
||||
},
|
||||
"transform-classes": {
|
||||
"chrome": "46",
|
||||
"opera": "33",
|
||||
"edge": "13",
|
||||
"firefox": "45",
|
||||
"safari": "10",
|
||||
"node": "5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.36"
|
||||
},
|
||||
"transform-object-super": {
|
||||
"chrome": "46",
|
||||
"opera": "33",
|
||||
"edge": "13",
|
||||
"firefox": "45",
|
||||
"safari": "10",
|
||||
"node": "5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.36"
|
||||
},
|
||||
"transform-shorthand-properties": {
|
||||
"chrome": "43",
|
||||
"opera": "30",
|
||||
"edge": "12",
|
||||
"firefox": "33",
|
||||
"safari": "9",
|
||||
"node": "4",
|
||||
"ios": "9",
|
||||
"samsung": "4",
|
||||
"electron": "0.27"
|
||||
},
|
||||
"transform-duplicate-keys": {
|
||||
"chrome": "42",
|
||||
"opera": "29",
|
||||
"edge": "12",
|
||||
"firefox": "34",
|
||||
"safari": "9",
|
||||
"node": "4",
|
||||
"ios": "9",
|
||||
"samsung": "3.4",
|
||||
"electron": "0.25"
|
||||
},
|
||||
"transform-computed-properties": {
|
||||
"chrome": "44",
|
||||
"opera": "31",
|
||||
"edge": "12",
|
||||
"firefox": "34",
|
||||
"safari": "7.1",
|
||||
"node": "4",
|
||||
"ios": "8",
|
||||
"samsung": "4",
|
||||
"electron": "0.30"
|
||||
},
|
||||
"transform-for-of": {
|
||||
"chrome": "51",
|
||||
"opera": "38",
|
||||
"edge": "15",
|
||||
"firefox": "53",
|
||||
"safari": "10",
|
||||
"node": "6.5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "1.2"
|
||||
},
|
||||
"transform-sticky-regex": {
|
||||
"chrome": "49",
|
||||
"opera": "36",
|
||||
"edge": "13",
|
||||
"firefox": "3",
|
||||
"safari": "10",
|
||||
"node": "6",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.37"
|
||||
},
|
||||
"transform-unicode-escapes": {
|
||||
"chrome": "44",
|
||||
"opera": "31",
|
||||
"edge": "12",
|
||||
"firefox": "53",
|
||||
"safari": "9",
|
||||
"node": "4",
|
||||
"ios": "9",
|
||||
"samsung": "4",
|
||||
"electron": "0.30"
|
||||
},
|
||||
"transform-unicode-regex": {
|
||||
"chrome": "50",
|
||||
"opera": "37",
|
||||
"edge": "13",
|
||||
"firefox": "46",
|
||||
"safari": "12",
|
||||
"node": "6",
|
||||
"ios": "12",
|
||||
"samsung": "5",
|
||||
"electron": "1.1"
|
||||
},
|
||||
"transform-spread": {
|
||||
"chrome": "46",
|
||||
"opera": "33",
|
||||
"edge": "13",
|
||||
"firefox": "45",
|
||||
"safari": "10",
|
||||
"node": "5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.36"
|
||||
},
|
||||
"transform-destructuring": {
|
||||
"chrome": "51",
|
||||
"opera": "38",
|
||||
"edge": "15",
|
||||
"firefox": "53",
|
||||
"safari": "10",
|
||||
"node": "6.5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "1.2"
|
||||
},
|
||||
"transform-block-scoping": {
|
||||
"chrome": "49",
|
||||
"opera": "36",
|
||||
"edge": "14",
|
||||
"firefox": "51",
|
||||
"safari": "11",
|
||||
"node": "6",
|
||||
"ios": "11",
|
||||
"samsung": "5",
|
||||
"electron": "0.37"
|
||||
},
|
||||
"transform-typeof-symbol": {
|
||||
"chrome": "38",
|
||||
"opera": "25",
|
||||
"edge": "12",
|
||||
"firefox": "36",
|
||||
"safari": "9",
|
||||
"node": "0.12",
|
||||
"ios": "9",
|
||||
"samsung": "3",
|
||||
"electron": "0.20"
|
||||
},
|
||||
"transform-new-target": {
|
||||
"chrome": "46",
|
||||
"opera": "33",
|
||||
"edge": "14",
|
||||
"firefox": "41",
|
||||
"safari": "10",
|
||||
"node": "5",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "0.36"
|
||||
},
|
||||
"transform-regenerator": {
|
||||
"chrome": "50",
|
||||
"opera": "37",
|
||||
"edge": "13",
|
||||
"firefox": "53",
|
||||
"safari": "10",
|
||||
"node": "6",
|
||||
"ios": "10",
|
||||
"samsung": "5",
|
||||
"electron": "1.1"
|
||||
},
|
||||
"transform-member-expression-literals": {
|
||||
"chrome": "7",
|
||||
"opera": "12",
|
||||
"edge": "12",
|
||||
"firefox": "2",
|
||||
"safari": "5.1",
|
||||
"node": "0.10",
|
||||
"ie": "9",
|
||||
"android": "4",
|
||||
"ios": "6",
|
||||
"phantom": "2",
|
||||
"samsung": "1",
|
||||
"electron": "0.20"
|
||||
},
|
||||
"transform-property-literals": {
|
||||
"chrome": "7",
|
||||
"opera": "12",
|
||||
"edge": "12",
|
||||
"firefox": "2",
|
||||
"safari": "5.1",
|
||||
"node": "0.10",
|
||||
"ie": "9",
|
||||
"android": "4",
|
||||
"ios": "6",
|
||||
"phantom": "2",
|
||||
"samsung": "1",
|
||||
"electron": "0.20"
|
||||
},
|
||||
"transform-reserved-words": {
|
||||
"chrome": "13",
|
||||
"opera": "10.50",
|
||||
"edge": "12",
|
||||
"firefox": "2",
|
||||
"safari": "3.1",
|
||||
"node": "0.10",
|
||||
"ie": "9",
|
||||
"android": "4.4",
|
||||
"ios": "6",
|
||||
"phantom": "2",
|
||||
"samsung": "1",
|
||||
"electron": "0.20"
|
||||
},
|
||||
"proposal-export-namespace-from": {
|
||||
"chrome": "72",
|
||||
"and_chr": "72",
|
||||
"edge": "79",
|
||||
"firefox": "80",
|
||||
"and_ff": "80",
|
||||
"node": "13.2",
|
||||
"opera": "60",
|
||||
"op_mob": "51",
|
||||
"samsung": "11.0",
|
||||
"android": "72",
|
||||
"electron": "5.0"
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./data/native-modules.json");
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./data/overlapping-plugins.json");
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "@babel/compat-data",
|
||||
"version": "7.14.5",
|
||||
"author": "The Babel Team (https://babel.dev/team)",
|
||||
"license": "MIT",
|
||||
"description": "",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/babel/babel.git",
|
||||
"directory": "packages/babel-compat-data"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"exports": {
|
||||
"./plugins": "./plugins.js",
|
||||
"./native-modules": "./native-modules.js",
|
||||
"./corejs2-built-ins": "./corejs2-built-ins.js",
|
||||
"./corejs3-shipped-proposals": "./corejs3-shipped-proposals.js",
|
||||
"./overlapping-plugins": "./overlapping-plugins.js",
|
||||
"./plugin-bugfixes": "./plugin-bugfixes.js"
|
||||
},
|
||||
"scripts": {
|
||||
"build-data": "./scripts/download-compat-table.sh && node ./scripts/build-data.js && node ./scripts/build-modules-support.js && node ./scripts/build-bugfixes-targets.js"
|
||||
},
|
||||
"keywords": [
|
||||
"babel",
|
||||
"compat-table",
|
||||
"compat-data"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@mdn/browser-compat-data": "^3.3.4",
|
||||
"core-js-compat": "^3.14.0",
|
||||
"electron-to-chromium": "^1.3.749"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./data/plugin-bugfixes.json");
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./data/plugins.json");
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014-present Sebastian McKenzie and other contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# @babel/core
|
||||
|
||||
> Babel compiler core.
|
||||
|
||||
See our website [@babel/core](https://babeljs.io/docs/en/babel-core) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen) associated with this package.
|
||||
|
||||
## Install
|
||||
|
||||
Using npm:
|
||||
|
||||
```sh
|
||||
npm install --save-dev @babel/core
|
||||
```
|
||||
|
||||
or using yarn:
|
||||
|
||||
```sh
|
||||
yarn add @babel/core --dev
|
||||
```
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.makeWeakCache = makeWeakCache;
|
||||
exports.makeWeakCacheSync = makeWeakCacheSync;
|
||||
exports.makeStrongCache = makeStrongCache;
|
||||
exports.makeStrongCacheSync = makeStrongCacheSync;
|
||||
exports.assertSimpleType = assertSimpleType;
|
||||
|
||||
function _gensync() {
|
||||
const data = require("gensync");
|
||||
|
||||
_gensync = function () {
|
||||
return data;
|
||||
};
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
var _async = require("../gensync-utils/async");
|
||||
|
||||
var _util = require("./util");
|
||||
|
||||
const synchronize = gen => {
|
||||
return _gensync()(gen).sync;
|
||||
};
|
||||
|
||||
function* genTrue() {
|
||||
return true;
|
||||
}
|
||||
|
||||
function makeWeakCache(handler) {
|
||||
return makeCachedFunction(WeakMap, handler);
|
||||
}
|
||||
|
||||
function makeWeakCacheSync(handler) {
|
||||
return synchronize(makeWeakCache(handler));
|
||||
}
|
||||
|
||||
function makeStrongCache(handler) {
|
||||
return makeCachedFunction(Map, handler);
|
||||
}
|
||||
|
||||
function makeStrongCacheSync(handler) {
|
||||
return synchronize(makeStrongCache(handler));
|
||||
}
|
||||
|
||||
function makeCachedFunction(CallCache, handler) {
|
||||
const callCacheSync = new CallCache();
|
||||
const callCacheAsync = new CallCache();
|
||||
const futureCache = new CallCache();
|
||||
return function* cachedFunction(arg, data) {
|
||||
const asyncContext = yield* (0, _async.isAsync)();
|
||||
const callCache = asyncContext ? callCacheAsync : callCacheSync;
|
||||
const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data);
|
||||
if (cached.valid) return cached.value;
|
||||
const cache = new CacheConfigurator(data);
|
||||
const handlerResult = handler(arg, cache);
|
||||
let finishLock;
|
||||
let value;
|
||||
|
||||
if ((0, _util.isIterableIterator)(handlerResult)) {
|
||||
const gen = handlerResult;
|
||||
value = yield* (0, _async.onFirstPause)(gen, () => {
|
||||
finishLock = setupAsyncLocks(cache, futureCache, arg);
|
||||
});
|
||||
} else {
|
||||
value = handlerResult;
|
||||
}
|
||||
|
||||
updateFunctionCache(callCache, cache, arg, value);
|
||||
|
||||
if (finishLock) {
|
||||
futureCache.delete(arg);
|
||||
finishLock.release(value);
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
function* getCachedValue(cache, arg, data) {
|
||||
const cachedValue = cache.get(arg);
|
||||
|
||||
if (cachedValue) {
|
||||
for (const {
|
||||
value,
|
||||
valid
|
||||
} of cachedValue) {
|
||||
if (yield* valid(data)) return {
|
||||
valid: true,
|
||||
value
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: false,
|
||||
value: null
|
||||
};
|
||||
}
|
||||
|
||||
function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) {
|
||||
const cached = yield* getCachedValue(callCache, arg, data);
|
||||
|
||||
if (cached.valid) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
if (asyncContext) {
|
||||
const cached = yield* getCachedValue(futureCache, arg, data);
|
||||
|
||||
if (cached.valid) {
|
||||
const value = yield* (0, _async.waitFor)(cached.value.promise);
|
||||
return {
|
||||
valid: true,
|
||||
value
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: false,
|
||||
value: null
|
||||
};
|
||||
}
|
||||
|
||||
function setupAsyncLocks(config, futureCache, arg) {
|
||||
const finishLock = new Lock();
|
||||
updateFunctionCache(futureCache, config, arg, finishLock);
|
||||
return finishLock;
|
||||
}
|
||||
|
||||
function updateFunctionCache(cache, config, arg, value) {
|
||||
if (!config.configured()) config.forever();
|
||||
let cachedValue = cache.get(arg);
|
||||
config.deactivate();
|
||||
|
||||
switch (config.mode()) {
|
||||
case "forever":
|
||||
cachedValue = [{
|
||||
value,
|
||||
valid: genTrue
|
||||
}];
|
||||
cache.set(arg, cachedValue);
|
||||
break;
|
||||
|
||||
case "invalidate":
|
||||
cachedValue = [{
|
||||
value,
|
||||
valid: config.validator()
|
||||
}];
|
||||
cache.set(arg, cachedValue);
|
||||
break;
|
||||
|
||||
case "valid":
|
||||
if (cachedValue) {
|
||||
cachedValue.push({
|
||||
value,
|
||||
valid: config.validator()
|
||||
});
|
||||
} else {
|
||||
cachedValue = [{
|
||||
value,
|
||||
valid: config.validator()
|
||||
}];
|
||||
cache.set(arg, cachedValue);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
class CacheConfigurator {
|
||||
constructor(data) {
|
||||
this._active = true;
|
||||
this._never = false;
|
||||
this._forever = false;
|
||||
this._invalidate = false;
|
||||
this._configured = false;
|
||||
this._pairs = [];
|
||||
this._data = void 0;
|
||||
this._data = data;
|
||||
}
|
||||
|
||||
simple() {
|
||||
return makeSimpleConfigurator(this);
|
||||
}
|
||||
|
||||
mode() {
|
||||
if (this._never) return "never";
|
||||
if (this._forever) return "forever";
|
||||
if (this._invalidate) return "invalidate";
|
||||
return "valid";
|
||||
}
|
||||
|
||||
forever() {
|
||||
if (!this._active) {
|
||||
throw new Error("Cannot change caching after evaluation has completed.");
|
||||
}
|
||||
|
||||
if (this._never) {
|
||||
throw new Error("Caching has already been configured with .never()");
|
||||
}
|
||||
|
||||
this._forever = true;
|
||||
this._configured = true;
|
||||
}
|
||||
|
||||
never() {
|
||||
if (!this._active) {
|
||||
throw new Error("Cannot change caching after evaluation has completed.");
|
||||
}
|
||||
|
||||
if (this._forever) {
|
||||
throw new Error("Caching has already been configured with .forever()");
|
||||
}
|
||||
|
||||
this._never = true;
|
||||
this._configured = true;
|
||||
}
|
||||
|
||||
using(handler) {
|
||||
if (!this._active) {
|
||||
throw new Error("Cannot change caching after evaluation has completed.");
|
||||
}
|
||||
|
||||
if (this._never || this._forever) {
|
||||
throw new Error("Caching has already been configured with .never or .forever()");
|
||||
}
|
||||
|
||||
this._configured = true;
|
||||
const key = handler(this._data);
|
||||
const fn = (0, _async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`);
|
||||
|
||||
if ((0, _async.isThenable)(key)) {
|
||||
return key.then(key => {
|
||||
this._pairs.push([key, fn]);
|
||||
|
||||
return key;
|
||||
});
|
||||
}
|
||||
|
||||
this._pairs.push([key, fn]);
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
invalidate(handler) {
|
||||
this._invalidate = true;
|
||||
return this.using(handler);
|
||||
}
|
||||
|
||||
validator() {
|
||||
const pairs = this._pairs;
|
||||
return function* (data) {
|
||||
for (const [key, fn] of pairs) {
|
||||
if (key !== (yield* fn(data))) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
deactivate() {
|
||||
this._active = false;
|
||||
}
|
||||
|
||||
configured() {
|
||||
return this._configured;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function makeSimpleConfigurator(cache) {
|
||||
function cacheFn(val) {
|
||||
if (typeof val === "boolean") {
|
||||
if (val) cache.forever();else cache.never();
|
||||
return;
|
||||
}
|
||||
|
||||
return cache.using(() => assertSimpleType(val()));
|
||||
}
|
||||
|
||||
cacheFn.forever = () => cache.forever();
|
||||
|
||||
cacheFn.never = () => cache.never();
|
||||
|
||||
cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
|
||||
|
||||
cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
|
||||
|
||||
return cacheFn;
|
||||
}
|
||||
|
||||
function assertSimpleType(value) {
|
||||
if ((0, _async.isThenable)(value)) {
|
||||
throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`);
|
||||
}
|
||||
|
||||
if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") {
|
||||
throw new Error("Cache keys must be either string, boolean, number, null, or undefined.");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
class Lock {
|
||||
constructor() {
|
||||
this.released = false;
|
||||
this.promise = void 0;
|
||||
this._resolve = void 0;
|
||||
this.promise = new Promise(resolve => {
|
||||
this._resolve = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
release(value) {
|
||||
this.released = true;
|
||||
|
||||
this._resolve(value);
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user