From b18d6c1d9ec70297a743bf4398417b6ff39ccdb5 Mon Sep 17 00:00:00 2001 From: CrazyMax <1951866+crazy-max@users.noreply.github.com> Date: Tue, 18 Jun 2024 11:31:30 +0200 Subject: [PATCH] push lib test Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com> --- .gitignore | 3 - lib/buildkit/buildkit.d.ts | 29 + lib/buildkit/buildkit.js | 135 +++++ lib/buildkit/buildkit.js.map | 1 + lib/buildkit/config.d.ts | 20 + lib/buildkit/config.js | 44 ++ lib/buildkit/config.js.map | 1 + lib/buildx/bake.d.ts | 47 ++ lib/buildx/bake.js | 160 ++++++ lib/buildx/bake.js.map | 1 + lib/buildx/build.d.ts | 49 ++ lib/buildx/build.js | 303 ++++++++++ lib/buildx/build.js.map | 1 + lib/buildx/builder.d.ts | 27 + lib/buildx/builder.js | 253 +++++++++ lib/buildx/builder.js.map | 1 + lib/buildx/buildx.d.ts | 42 ++ lib/buildx/buildx.js | 245 ++++++++ lib/buildx/buildx.js.map | 1 + lib/buildx/history.d.ts | 27 + lib/buildx/history.js | 186 ++++++ lib/buildx/history.js.map | 1 + lib/buildx/install.d.ts | 34 ++ lib/buildx/install.js | 333 +++++++++++ lib/buildx/install.js.map | 1 + lib/cache.d.ts | 40 ++ lib/cache.js | 148 +++++ lib/cache.js.map | 1 + lib/context.d.ts | 25 + lib/context.js | 81 +++ lib/context.js.map | 1 + lib/docker/assets.d.ts | 21 + lib/docker/assets.js | 259 +++++++++ lib/docker/assets.js.map | 1 + lib/docker/docker.d.ts | 29 + lib/docker/docker.js | 205 +++++++ lib/docker/docker.js.map | 1 + lib/docker/install.d.ts | 57 ++ lib/docker/install.js | 535 ++++++++++++++++++ lib/docker/install.js.map | 1 + lib/dockerhub.d.ts | 31 + lib/dockerhub.js | 156 +++++ lib/dockerhub.js.map | 1 + lib/exec.d.ts | 20 + lib/exec.js | 68 +++ lib/exec.js.map | 1 + lib/git.d.ts | 29 + lib/git.js | 201 +++++++ lib/git.js.map | 1 + lib/github.d.ts | 37 ++ lib/github.js | 296 ++++++++++ lib/github.js.map | 1 + lib/index.d.ts | 24 + lib/index.js | 86 +++ lib/index.js.map | 1 + lib/oci/oci.d.ts | 9 + lib/oci/oci.js | 199 +++++++ lib/oci/oci.js.map | 1 + lib/toolkit.d.ts | 39 ++ lib/toolkit.js | 38 ++ lib/toolkit.js.map | 1 + lib/types/buildkit/buildkit.d.ts | 16 + lib/types/buildkit/buildkit.js | 21 + lib/types/buildkit/buildkit.js.map | 1 + lib/types/buildkit/client.d.ts | 61 ++ lib/types/buildkit/client.js | 18 + lib/types/buildkit/client.js.map | 1 + lib/types/buildkit/control.d.ts | 88 +++ lib/types/buildkit/control.js | 18 + lib/types/buildkit/control.js.map | 1 + lib/types/buildkit/ops.d.ts | 60 ++ lib/types/buildkit/ops.js | 18 + lib/types/buildkit/ops.js.map | 1 + lib/types/buildkit/rpc.d.ts | 24 + lib/types/buildkit/rpc.js | 18 + lib/types/buildkit/rpc.js.map | 1 + lib/types/buildx/bake.d.ts | 47 ++ lib/types/buildx/bake.js | 18 + lib/types/buildx/bake.js.map | 1 + lib/types/buildx/build.d.ts | 18 + lib/types/buildx/build.js | 18 + lib/types/buildx/build.js.map | 1 + lib/types/buildx/builder.d.ts | 41 ++ lib/types/buildx/builder.js | 18 + lib/types/buildx/builder.js.map | 1 + lib/types/buildx/buildx.d.ts | 41 ++ lib/types/buildx/buildx.js | 18 + lib/types/buildx/buildx.js.map | 1 + lib/types/buildx/history.d.ts | 40 ++ lib/types/buildx/history.js | 18 + lib/types/buildx/history.js.map | 1 + lib/types/docker/docker.d.ts | 61 ++ lib/types/docker/docker.js | 18 + lib/types/docker/docker.js.map | 1 + lib/types/dockerhub.d.ts | 104 ++++ lib/types/dockerhub.js | 18 + lib/types/dockerhub.js.map | 1 + lib/types/git.d.ts | 17 + lib/types/git.js | 18 + lib/types/git.js.map | 1 + lib/types/github.d.ts | 50 ++ lib/types/github.js | 18 + lib/types/github.js.map | 1 + lib/types/intoto/intoto.d.ts | 17 + lib/types/intoto/intoto.js | 22 + lib/types/intoto/intoto.js.map | 1 + .../slsa_provenance/v0.2/provenance.d.ts | 55 ++ .../intoto/slsa_provenance/v0.2/provenance.js | 21 + .../slsa_provenance/v0.2/provenance.js.map | 1 + lib/types/oci/config.d.ts | 47 ++ lib/types/oci/config.js | 18 + lib/types/oci/config.js.map | 1 + lib/types/oci/descriptor.d.ts | 34 ++ lib/types/oci/descriptor.js | 26 + lib/types/oci/descriptor.js.map | 1 + lib/types/oci/digest.d.ts | 16 + lib/types/oci/digest.js | 18 + lib/types/oci/digest.js.map | 1 + lib/types/oci/index.d.ts | 24 + lib/types/oci/index.js | 18 + lib/types/oci/index.js.map | 1 + lib/types/oci/layout.d.ts | 22 + lib/types/oci/layout.js | 23 + lib/types/oci/layout.js.map | 1 + lib/types/oci/manifest.d.ts | 25 + lib/types/oci/manifest.js | 18 + lib/types/oci/manifest.js.map | 1 + lib/types/oci/mediatype.d.ts | 20 + lib/types/oci/mediatype.js | 24 + lib/types/oci/mediatype.js.map | 1 + lib/types/oci/oci.d.ts | 32 ++ lib/types/oci/oci.js | 18 + lib/types/oci/oci.js.map | 1 + lib/types/oci/versioned.d.ts | 18 + lib/types/oci/versioned.js | 18 + lib/types/oci/versioned.js.map | 1 + lib/util.d.ts | 41 ++ lib/util.js | 213 +++++++ lib/util.js.map | 1 + 139 files changed, 6324 insertions(+), 3 deletions(-) create mode 100644 lib/buildkit/buildkit.d.ts create mode 100644 lib/buildkit/buildkit.js create mode 100644 lib/buildkit/buildkit.js.map create mode 100644 lib/buildkit/config.d.ts create mode 100644 lib/buildkit/config.js create mode 100644 lib/buildkit/config.js.map create mode 100644 lib/buildx/bake.d.ts create mode 100644 lib/buildx/bake.js create mode 100644 lib/buildx/bake.js.map create mode 100644 lib/buildx/build.d.ts create mode 100644 lib/buildx/build.js create mode 100644 lib/buildx/build.js.map create mode 100644 lib/buildx/builder.d.ts create mode 100644 lib/buildx/builder.js create mode 100644 lib/buildx/builder.js.map create mode 100644 lib/buildx/buildx.d.ts create mode 100644 lib/buildx/buildx.js create mode 100644 lib/buildx/buildx.js.map create mode 100644 lib/buildx/history.d.ts create mode 100644 lib/buildx/history.js create mode 100644 lib/buildx/history.js.map create mode 100644 lib/buildx/install.d.ts create mode 100644 lib/buildx/install.js create mode 100644 lib/buildx/install.js.map create mode 100644 lib/cache.d.ts create mode 100644 lib/cache.js create mode 100644 lib/cache.js.map create mode 100644 lib/context.d.ts create mode 100644 lib/context.js create mode 100644 lib/context.js.map create mode 100644 lib/docker/assets.d.ts create mode 100644 lib/docker/assets.js create mode 100644 lib/docker/assets.js.map create mode 100644 lib/docker/docker.d.ts create mode 100644 lib/docker/docker.js create mode 100644 lib/docker/docker.js.map create mode 100644 lib/docker/install.d.ts create mode 100644 lib/docker/install.js create mode 100644 lib/docker/install.js.map create mode 100644 lib/dockerhub.d.ts create mode 100644 lib/dockerhub.js create mode 100644 lib/dockerhub.js.map create mode 100644 lib/exec.d.ts create mode 100644 lib/exec.js create mode 100644 lib/exec.js.map create mode 100644 lib/git.d.ts create mode 100644 lib/git.js create mode 100644 lib/git.js.map create mode 100644 lib/github.d.ts create mode 100644 lib/github.js create mode 100644 lib/github.js.map create mode 100644 lib/index.d.ts create mode 100644 lib/index.js create mode 100644 lib/index.js.map create mode 100644 lib/oci/oci.d.ts create mode 100644 lib/oci/oci.js create mode 100644 lib/oci/oci.js.map create mode 100644 lib/toolkit.d.ts create mode 100644 lib/toolkit.js create mode 100644 lib/toolkit.js.map create mode 100644 lib/types/buildkit/buildkit.d.ts create mode 100644 lib/types/buildkit/buildkit.js create mode 100644 lib/types/buildkit/buildkit.js.map create mode 100644 lib/types/buildkit/client.d.ts create mode 100644 lib/types/buildkit/client.js create mode 100644 lib/types/buildkit/client.js.map create mode 100644 lib/types/buildkit/control.d.ts create mode 100644 lib/types/buildkit/control.js create mode 100644 lib/types/buildkit/control.js.map create mode 100644 lib/types/buildkit/ops.d.ts create mode 100644 lib/types/buildkit/ops.js create mode 100644 lib/types/buildkit/ops.js.map create mode 100644 lib/types/buildkit/rpc.d.ts create mode 100644 lib/types/buildkit/rpc.js create mode 100644 lib/types/buildkit/rpc.js.map create mode 100644 lib/types/buildx/bake.d.ts create mode 100644 lib/types/buildx/bake.js create mode 100644 lib/types/buildx/bake.js.map create mode 100644 lib/types/buildx/build.d.ts create mode 100644 lib/types/buildx/build.js create mode 100644 lib/types/buildx/build.js.map create mode 100644 lib/types/buildx/builder.d.ts create mode 100644 lib/types/buildx/builder.js create mode 100644 lib/types/buildx/builder.js.map create mode 100644 lib/types/buildx/buildx.d.ts create mode 100644 lib/types/buildx/buildx.js create mode 100644 lib/types/buildx/buildx.js.map create mode 100644 lib/types/buildx/history.d.ts create mode 100644 lib/types/buildx/history.js create mode 100644 lib/types/buildx/history.js.map create mode 100644 lib/types/docker/docker.d.ts create mode 100644 lib/types/docker/docker.js create mode 100644 lib/types/docker/docker.js.map create mode 100644 lib/types/dockerhub.d.ts create mode 100644 lib/types/dockerhub.js create mode 100644 lib/types/dockerhub.js.map create mode 100644 lib/types/git.d.ts create mode 100644 lib/types/git.js create mode 100644 lib/types/git.js.map create mode 100644 lib/types/github.d.ts create mode 100644 lib/types/github.js create mode 100644 lib/types/github.js.map create mode 100644 lib/types/intoto/intoto.d.ts create mode 100644 lib/types/intoto/intoto.js create mode 100644 lib/types/intoto/intoto.js.map create mode 100644 lib/types/intoto/slsa_provenance/v0.2/provenance.d.ts create mode 100644 lib/types/intoto/slsa_provenance/v0.2/provenance.js create mode 100644 lib/types/intoto/slsa_provenance/v0.2/provenance.js.map create mode 100644 lib/types/oci/config.d.ts create mode 100644 lib/types/oci/config.js create mode 100644 lib/types/oci/config.js.map create mode 100644 lib/types/oci/descriptor.d.ts create mode 100644 lib/types/oci/descriptor.js create mode 100644 lib/types/oci/descriptor.js.map create mode 100644 lib/types/oci/digest.d.ts create mode 100644 lib/types/oci/digest.js create mode 100644 lib/types/oci/digest.js.map create mode 100644 lib/types/oci/index.d.ts create mode 100644 lib/types/oci/index.js create mode 100644 lib/types/oci/index.js.map create mode 100644 lib/types/oci/layout.d.ts create mode 100644 lib/types/oci/layout.js create mode 100644 lib/types/oci/layout.js.map create mode 100644 lib/types/oci/manifest.d.ts create mode 100644 lib/types/oci/manifest.js create mode 100644 lib/types/oci/manifest.js.map create mode 100644 lib/types/oci/mediatype.d.ts create mode 100644 lib/types/oci/mediatype.js create mode 100644 lib/types/oci/mediatype.js.map create mode 100644 lib/types/oci/oci.d.ts create mode 100644 lib/types/oci/oci.js create mode 100644 lib/types/oci/oci.js.map create mode 100644 lib/types/oci/versioned.d.ts create mode 100644 lib/types/oci/versioned.js create mode 100644 lib/types/oci/versioned.js.map create mode 100644 lib/util.d.ts create mode 100644 lib/util.js create mode 100644 lib/util.js.map diff --git a/.gitignore b/.gitignore index 4b3170ee..4814714d 100644 --- a/.gitignore +++ b/.gitignore @@ -51,6 +51,3 @@ jspm_packages/ .yarn/build-state.yml .yarn/install-state.gz .pnp.* - -# Lib -/lib diff --git a/lib/buildkit/buildkit.d.ts b/lib/buildkit/buildkit.d.ts new file mode 100644 index 00000000..f53c0b1f --- /dev/null +++ b/lib/buildkit/buildkit.d.ts @@ -0,0 +1,29 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Buildx } from '../buildx/buildx'; +import { Config } from './config'; +import { BuilderInfo, NodeInfo } from '../types/buildx/builder'; +export interface BuildKitOpts { + buildx?: Buildx; +} +export declare class BuildKit { + private readonly buildx; + readonly config: Config; + constructor(opts?: BuildKitOpts); + getVersion(node: NodeInfo): Promise; + private getVersionWithinImage; + versionSatisfies(builderName: string, range: string, builderInfo?: BuilderInfo): Promise; +} diff --git a/lib/buildkit/buildkit.js b/lib/buildkit/buildkit.js new file mode 100644 index 00000000..be4ad463 --- /dev/null +++ b/lib/buildkit/buildkit.js @@ -0,0 +1,135 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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.BuildKit = void 0; +const core = __importStar(require("@actions/core")); +const semver = __importStar(require("semver")); +const buildx_1 = require("../buildx/buildx"); +const builder_1 = require("../buildx/builder"); +const config_1 = require("./config"); +const exec_1 = require("../exec"); +class BuildKit { + constructor(opts) { + this.config = new config_1.Config(); + this.buildx = (opts === null || opts === void 0 ? void 0 : opts.buildx) || new buildx_1.Buildx(); + } + getVersion(node) { + return __awaiter(this, void 0, void 0, function* () { + if (!node.buildkit && node.name) { + try { + return yield this.getVersionWithinImage(node.name); + } + catch (e) { + core.warning(e); + } + } + return node.buildkit; + }); + } + getVersionWithinImage(nodeName) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`BuildKit.getVersionWithinImage nodeName: ${nodeName}`); + return exec_1.Exec.getExecOutput(`docker`, ['inspect', '--format', '{{.Config.Image}}', `${buildx_1.Buildx.containerNamePrefix}${nodeName}`], { + ignoreReturnCode: true, + silent: true + }).then(bkitimage => { + if (bkitimage.exitCode == 0 && bkitimage.stdout.length > 0) { + core.debug(`BuildKit.getVersionWithinImage image: ${bkitimage.stdout.trim()}`); + return exec_1.Exec.getExecOutput(`docker`, ['run', '--rm', bkitimage.stdout.trim(), '--version'], { + ignoreReturnCode: true, + silent: true + }).then(bkitversion => { + if (bkitversion.exitCode == 0 && bkitversion.stdout.length > 0) { + return `${bkitimage.stdout.trim()} => ${bkitversion.stdout.trim()}`; + } + else if (bkitversion.stderr.length > 0) { + throw new Error(bkitimage.stderr.trim()); + } + return bkitversion.stdout.trim(); + }); + } + else if (bkitimage.stderr.length > 0) { + throw new Error(bkitimage.stderr.trim()); + } + return bkitimage.stdout.trim(); + }); + }); + } + versionSatisfies(builderName, range, builderInfo) { + return __awaiter(this, void 0, void 0, function* () { + if (!builderInfo) { + builderInfo = yield new builder_1.Builder({ buildx: this.buildx }).inspect(builderName); + } + for (const node of builderInfo.nodes) { + let bkversion = node.buildkit; + core.debug(`BuildKit.versionSatisfies ${bkversion}: ${range}`); + if (!bkversion) { + try { + bkversion = yield this.getVersionWithinImage(node.name || ''); + } + catch (e) { + core.debug(`BuildKit.versionSatisfies ${node.name}: can't get version`); + return false; + } + } + core.debug(`BuildKit.versionSatisfies ${node.name}: version ${bkversion}`); + // BuildKit version reported by moby is in the format of `v0.11.0-moby` + if (builderInfo.driver == 'docker' && !bkversion.endsWith('-moby')) { + return false; + } + if (!semver.satisfies(bkversion.replace(/-moby$/, ''), range)) { + return false; + } + } + return true; + }); + } +} +exports.BuildKit = BuildKit; +//# sourceMappingURL=buildkit.js.map \ No newline at end of file diff --git a/lib/buildkit/buildkit.js.map b/lib/buildkit/buildkit.js.map new file mode 100644 index 00000000..d8d0d68e --- /dev/null +++ b/lib/buildkit/buildkit.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buildkit.js","sourceRoot":"","sources":["../../src/buildkit/buildkit.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAAsC;AACtC,+CAAiC;AAEjC,6CAAwC;AACxC,+CAA0C;AAC1C,qCAAgC;AAChC,kCAA6B;AAQ7B,MAAa,QAAQ;IAKnB,YAAY,IAAmB;QAC7B,IAAI,CAAC,MAAM,GAAG,IAAI,eAAM,EAAE,CAAC;QAC3B,IAAI,CAAC,MAAM,GAAG,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,KAAI,IAAI,eAAM,EAAE,CAAC;IAC7C,CAAC;IAEY,UAAU,CAAC,IAAc;;YACpC,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;gBAChC,IAAI,CAAC;oBACH,OAAO,MAAM,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACrD,CAAC;gBAAC,OAAO,CAAC,EAAE,CAAC;o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CAAC,CAAC;gBAC3E,uEAAuE;gBACvE,IAAI,WAAW,CAAC,MAAM,IAAI,QAAQ,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;oBACnE,OAAO,KAAK,CAAC;gBACf,CAAC;gBACD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC;oBAC9D,OAAO,KAAK,CAAC;gBACf,CAAC;YACH,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;KAAA;CACF;AAzED,4BAyEC"} \ No newline at end of file diff --git a/lib/buildkit/config.d.ts b/lib/buildkit/config.d.ts new file mode 100644 index 00000000..b4a8f511 --- /dev/null +++ b/lib/buildkit/config.d.ts @@ -0,0 +1,20 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class Config { + resolveFromString(s: string): string; + resolveFromFile(s: string): string; + private resolve; +} diff --git a/lib/buildkit/config.js b/lib/buildkit/config.js new file mode 100644 index 00000000..5b829eac --- /dev/null +++ b/lib/buildkit/config.js @@ -0,0 +1,44 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Config = void 0; +const fs_1 = __importDefault(require("fs")); +const context_1 = require("../context"); +class Config { + resolveFromString(s) { + return this.resolve(s, false); + } + resolveFromFile(s) { + return this.resolve(s, true); + } + resolve(s, file) { + if (file) { + if (!fs_1.default.existsSync(s)) { + throw new Error(`config file ${s} not found`); + } + s = fs_1.default.readFileSync(s, { encoding: 'utf-8' }); + } + const configFile = context_1.Context.tmpName({ tmpdir: context_1.Context.tmpDir() }); + fs_1.default.writeFileSync(configFile, s); + return configFile; + } +} +exports.Config = Config; +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/lib/buildkit/config.js.map b/lib/buildkit/config.js.map new file mode 100644 index 00000000..ec8eb53e --- /dev/null +++ b/lib/buildkit/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/buildkit/config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;AAEH,4CAAoB;AAEpB,wCAAmC;AAEnC,MAAa,MAAM;IACV,iBAAiB,CAAC,CAAS;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IAChC,CAAC;IAEM,eAAe,CAAC,CAAS;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;IAEO,OAAO,CAAC,CAAS,EAAE,IAAa;QACtC,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;gBACtB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC;YAChD,CAAC;YACD,CAAC,GAAG,YAAE,CAAC,YAAY,CAAC,CAAC,EAAE,EAAC,QAAQ,EAAE,OAAO,EAAC,CAAC,CAAC;QAC9C,CAAC;QACD,MAAM,UAAU,GAAG,iBAAO,CAAC,OAAO,CAAC,EAAC,MAAM,EAAE,iBAAO,CAAC,MAAM,EAAE,EAAC,CAAC,CAAC;QAC/D,YAAE,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;QAChC,OAAO,UAAU,CAAC;IACpB,CAAC;CACF;AApBD,wBAoBC"} \ No newline at end of file diff --git a/lib/buildx/bake.d.ts b/lib/buildx/bake.d.ts new file mode 100644 index 00000000..d29df4d7 --- /dev/null +++ b/lib/buildx/bake.d.ts @@ -0,0 +1,47 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Buildx } from './buildx'; +import { ExecOptions } from '@actions/exec'; +import { BakeDefinition, BakeMetadata } from '../types/buildx/bake'; +export interface BakeOpts { + buildx?: Buildx; +} +export interface BakeCmdOpts { + files?: Array; + load?: boolean; + noCache?: boolean; + overrides?: Array; + provenance?: string; + push?: boolean; + sbom?: string; + source?: string; + targets?: Array; + githubToken?: string; +} +export declare class Bake { + private readonly buildx; + private readonly metadataFilename; + constructor(opts?: BakeOpts); + getMetadataFilePath(): string; + resolveMetadata(): BakeMetadata | undefined; + resolveRefs(metadata?: BakeMetadata): Array | undefined; + getDefinition(cmdOpts: BakeCmdOpts, execOptions?: ExecOptions): Promise; + static parseDefinition(dt: string): BakeDefinition; + static hasLocalExporter(def: BakeDefinition): boolean; + static hasTarExporter(def: BakeDefinition): boolean; + static hasDockerExporter(def: BakeDefinition, load?: boolean): boolean; + private static exporters; +} diff --git a/lib/buildx/bake.js b/lib/buildx/bake.js new file mode 100644 index 00000000..14dd75a0 --- /dev/null +++ b/lib/buildx/bake.js @@ -0,0 +1,160 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Bake = void 0; +const fs_1 = __importDefault(require("fs")); +const path_1 = __importDefault(require("path")); +const build_1 = require("./build"); +const buildx_1 = require("./buildx"); +const context_1 = require("../context"); +const exec_1 = require("../exec"); +const util_1 = require("../util"); +class Bake { + constructor(opts) { + this.buildx = (opts === null || opts === void 0 ? void 0 : opts.buildx) || new buildx_1.Buildx(); + this.metadataFilename = `bake-metadata-${util_1.Util.generateRandomString()}.json`; + } + getMetadataFilePath() { + return path_1.default.join(context_1.Context.tmpDir(), this.metadataFilename); + } + resolveMetadata() { + const metadataFile = this.getMetadataFilePath(); + if (!fs_1.default.existsSync(metadataFile)) { + return undefined; + } + const content = fs_1.default.readFileSync(metadataFile, { encoding: 'utf-8' }).trim(); + if (content === 'null') { + return undefined; + } + return JSON.parse(content); + } + resolveRefs(metadata) { + if (!metadata) { + metadata = this.resolveMetadata(); + if (!metadata) { + return undefined; + } + } + const refs = new Array(); + for (const key in metadata) { + if ('buildx.build.ref' in metadata[key]) { + refs.push(metadata[key]['buildx.build.ref']); + } + } + return refs; + } + getDefinition(cmdOpts, execOptions) { + return __awaiter(this, void 0, void 0, function* () { + execOptions = execOptions || { ignoreReturnCode: true }; + execOptions.ignoreReturnCode = true; + if (cmdOpts.githubToken) { + execOptions.env = Object.assign({}, process.env, { + BUILDX_BAKE_GIT_AUTH_TOKEN: cmdOpts.githubToken + }); + } + const args = ['bake']; + let remoteDef; + const files = []; + const sources = [...(cmdOpts.files || []), cmdOpts.source]; + if (sources) { + for (const source of sources.map(v => (v ? v.trim() : ''))) { + if (source.length == 0) { + continue; + } + if (!util_1.Util.isValidRef(source)) { + files.push(source); + continue; + } + if (remoteDef) { + throw new Error(`Only one remote bake definition can be defined`); + } + remoteDef = source; + } + } + if (remoteDef) { + args.push(remoteDef); + } + for (const file of files) { + args.push('--file', file); + } + if (cmdOpts.overrides) { + for (const override of cmdOpts.overrides) { + args.push('--set', override); + } + } + if (cmdOpts.load) { + args.push('--load'); + } + if (cmdOpts.noCache) { + args.push('--no-cache'); + } + if (cmdOpts.provenance) { + args.push('--provenance', cmdOpts.provenance); + } + if (cmdOpts.push) { + args.push('--push'); + } + if (cmdOpts.sbom) { + args.push('--sbom', cmdOpts.sbom); + } + const printCmd = yield this.buildx.getCommand([...args, '--print', ...(cmdOpts.targets || [])]); + return yield exec_1.Exec.getExecOutput(printCmd.command, printCmd.args, execOptions).then(res => { + var _a, _b, _c; + if (res.stderr.length > 0 && res.exitCode != 0) { + throw new Error(`cannot parse bake definitions: ${(_c = (_b = (_a = res.stderr.match(/(.*)\s*$/)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : 'unknown error'}`); + } + return Bake.parseDefinition(res.stdout.trim()); + }); + }); + } + static parseDefinition(dt) { + return JSON.parse(dt); + } + static hasLocalExporter(def) { + return build_1.Build.hasExporterType('local', Bake.exporters(def)); + } + static hasTarExporter(def) { + return build_1.Build.hasExporterType('tar', Bake.exporters(def)); + } + static hasDockerExporter(def, load) { + return load || build_1.Build.hasExporterType('docker', Bake.exporters(def)); + } + static exporters(def) { + const exporters = new Array(); + for (const key in def.target) { + const target = def.target[key]; + if (target.output) { + exporters.push(...target.output); + } + } + return exporters; + } +} +exports.Bake = Bake; +//# sourceMappingURL=bake.js.map \ No newline at end of file diff --git a/lib/buildx/bake.js.map b/lib/buildx/bake.js.map new file mode 100644 index 00000000..070a685d --- /dev/null +++ b/lib/buildx/bake.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bake.js","sourceRoot":"","sources":["../../src/buildx/bake.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;AAEH,4CAAoB;AACpB,gDAAwB;AAExB,mCAA8B;AAC9B,qCAAgC;AAChC,wCAAmC;AACnC,kCAA6B;AAC7B,kCAA6B;AAuB7B,MAAa,IAAI;IAIf,YAAY,IAAe;QACzB,IAAI,CAAC,MAAM,GAAG,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,KAAI,IAAI,eAAM,EAAE,CAAC;QAC3C,IAAI,CAAC,gBAAgB,GAAG,iBAAiB,WAAI,CAAC,oBAAoB,EAAE,OAAO,CAAC;IAC9E,CAAC;IAEM,mBAAmB;QACxB,OAAO,cAAI,CAAC,IAAI,CAAC,iBAAO,CAAC,MAAM,EAAE,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAC;IAC5D,CAAC;IAEM,eAAe;QACpB,MAAM,YAAY,GAAG,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAChD,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;YACjC,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,OAAO,GAAG,YAAE,CAAC,YAAY,CAAC,Y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,MAAM,CAAC,gBAAgB,CAAC,GAAmB;QAChD,OAAO,aAAK,CAAC,eAAe,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7D,CAAC;IAEM,MAAM,CAAC,cAAc,CAAC,GAAmB;QAC9C,OAAO,aAAK,CAAC,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3D,CAAC;IAEM,MAAM,CAAC,iBAAiB,CAAC,GAAmB,EAAE,IAAc;QACjE,OAAO,IAAI,IAAI,aAAK,CAAC,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;IACtE,CAAC;IAEO,MAAM,CAAC,SAAS,CAAC,GAAmB;QAC1C,MAAM,SAAS,GAAG,IAAI,KAAK,EAAU,CAAC;QACtC,KAAK,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;YAC7B,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC/B,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;gBAClB,SAAS,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;YACnC,CAAC;QACH,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAtID,oBAsIC"} \ No newline at end of file diff --git a/lib/buildx/build.d.ts b/lib/buildx/build.d.ts new file mode 100644 index 00000000..4aa73917 --- /dev/null +++ b/lib/buildx/build.d.ts @@ -0,0 +1,49 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Buildx } from './buildx'; +import { BuildMetadata } from '../types/buildx/build'; +import { ProvenancePredicate } from '../types/intoto/slsa_provenance/v0.2/provenance'; +export interface BuildOpts { + buildx?: Buildx; +} +export declare class Build { + private readonly buildx; + private readonly iidFilename; + private readonly metadataFilename; + constructor(opts?: BuildOpts); + getImageIDFilePath(): string; + resolveImageID(): string | undefined; + getMetadataFilePath(): string; + resolveMetadata(): BuildMetadata | undefined; + resolveRef(metadata?: BuildMetadata): string | undefined; + resolveProvenance(metadata?: BuildMetadata): ProvenancePredicate | undefined; + resolveDigest(metadata?: BuildMetadata): string | undefined; + static resolveSecretString(kvp: string): string; + static resolveSecretFile(kvp: string): string; + static resolveSecretEnv(kvp: string): string; + static resolveSecret(kvp: string, file: boolean): [string, string]; + static getProvenanceInput(name: string): string; + static resolveProvenanceAttrs(input: string): string; + static resolveCacheToAttrs(input: string, githubToken?: string): string; + static hasLocalExporter(exporters: string[]): boolean; + static hasTarExporter(exporters: string[]): boolean; + static hasDockerExporter(exporters: string[], load?: boolean): boolean; + static hasExporterType(name: string, exporters: string[]): boolean; + static hasAttestationType(name: string, attrs: string): boolean; + static resolveAttestationAttrs(attrs: string): string; + static hasGitAuthTokenSecret(secrets: string[]): boolean; + private static parseSecretKvp; +} diff --git a/lib/buildx/build.js b/lib/buildx/build.js new file mode 100644 index 00000000..5d52e2fb --- /dev/null +++ b/lib/buildx/build.js @@ -0,0 +1,303 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Build = void 0; +const fs_1 = __importDefault(require("fs")); +const path_1 = __importDefault(require("path")); +const core = __importStar(require("@actions/core")); +const sync_1 = require("csv-parse/sync"); +const buildx_1 = require("./buildx"); +const context_1 = require("../context"); +const github_1 = require("../github"); +const util_1 = require("../util"); +class Build { + constructor(opts) { + this.buildx = (opts === null || opts === void 0 ? void 0 : opts.buildx) || new buildx_1.Buildx(); + this.iidFilename = `build-iidfile-${util_1.Util.generateRandomString()}.txt`; + this.metadataFilename = `build-metadata-${util_1.Util.generateRandomString()}.json`; + } + getImageIDFilePath() { + return path_1.default.join(context_1.Context.tmpDir(), this.iidFilename); + } + resolveImageID() { + const iidFile = this.getImageIDFilePath(); + if (!fs_1.default.existsSync(iidFile)) { + return undefined; + } + return fs_1.default.readFileSync(iidFile, { encoding: 'utf-8' }).trim(); + } + getMetadataFilePath() { + return path_1.default.join(context_1.Context.tmpDir(), this.metadataFilename); + } + resolveMetadata() { + const metadataFile = this.getMetadataFilePath(); + if (!fs_1.default.existsSync(metadataFile)) { + return undefined; + } + const content = fs_1.default.readFileSync(metadataFile, { encoding: 'utf-8' }).trim(); + if (content === 'null') { + return undefined; + } + return JSON.parse(content); + } + resolveRef(metadata) { + if (!metadata) { + metadata = this.resolveMetadata(); + if (!metadata) { + return undefined; + } + } + if ('buildx.build.ref' in metadata) { + return metadata['buildx.build.ref']; + } + return undefined; + } + resolveProvenance(metadata) { + if (!metadata) { + metadata = this.resolveMetadata(); + if (!metadata) { + return undefined; + } + } + if ('buildx.build.provenance' in metadata) { + return metadata['buildx.build.provenance']; + } + return undefined; + } + resolveDigest(metadata) { + if (!metadata) { + metadata = this.resolveMetadata(); + if (!metadata) { + return undefined; + } + } + if ('containerimage.digest' in metadata) { + return metadata['containerimage.digest']; + } + return undefined; + } + static resolveSecretString(kvp) { + const [key, file] = Build.resolveSecret(kvp, false); + return `id=${key},src=${file}`; + } + static resolveSecretFile(kvp) { + const [key, file] = Build.resolveSecret(kvp, true); + return `id=${key},src=${file}`; + } + static resolveSecretEnv(kvp) { + const [key, value] = Build.parseSecretKvp(kvp); + return `id=${key},env=${value}`; + } + static resolveSecret(kvp, file) { + const [key, _value] = Build.parseSecretKvp(kvp); + let value = _value; + if (file) { + if (!fs_1.default.existsSync(value)) { + throw new Error(`secret file ${value} not found`); + } + value = fs_1.default.readFileSync(value, { encoding: 'utf-8' }); + } + const secretFile = context_1.Context.tmpName({ tmpdir: context_1.Context.tmpDir() }); + fs_1.default.writeFileSync(secretFile, value); + return [key, secretFile]; + } + static getProvenanceInput(name) { + const input = core.getInput(name); + if (!input) { + // if input is not set returns empty string + return input; + } + try { + return core.getBooleanInput(name) ? `builder-id=${github_1.GitHub.workflowRunURL(true)}` : 'false'; + } + catch (err) { + // not a valid boolean, so we assume it's a string + return Build.resolveProvenanceAttrs(input); + } + } + static resolveProvenanceAttrs(input) { + if (!input) { + return `builder-id=${github_1.GitHub.workflowRunURL(true)}`; + } + // parse attributes from input + const fields = (0, sync_1.parse)(input, { + relaxColumnCount: true, + skipEmptyLines: true + })[0]; + // check if builder-id attribute exists in the input + for (const field of fields) { + const parts = field + .toString() + .split(/(?<=^[^=]+?)=/) + .map(item => item.trim()); + if (parts[0] == 'builder-id') { + return input; + } + } + // if not add builder-id attribute + return `${input},builder-id=${github_1.GitHub.workflowRunURL(true)}`; + } + static resolveCacheToAttrs(input, githubToken) { + if (!input) { + return input; + } + let cacheType = 'registry'; + let ghaCacheRepository = ''; + let ghaCacheGHToken = ''; + const fields = (0, sync_1.parse)(input, { + relaxColumnCount: true, + skipEmptyLines: true + })[0]; + for (const field of fields) { + const parts = field + .toString() + .split(/(?<=^[^=]+?)=/) + .map(item => item.trim()); + if (parts[0] === 'type') { + cacheType = parts[1]; + } + else if (parts[0] === 'repository') { + ghaCacheRepository = parts[1]; + } + else if (parts[0] === 'ghtoken') { + ghaCacheGHToken = parts[1]; + } + } + if (cacheType === 'gha') { + if (!ghaCacheRepository) { + input = `${input},repository=${github_1.GitHub.repository}`; + } + if (!ghaCacheGHToken && githubToken) { + input = `${input},ghtoken=${githubToken}`; + } + } + return input; + } + static hasLocalExporter(exporters) { + return Build.hasExporterType('local', exporters); + } + static hasTarExporter(exporters) { + return Build.hasExporterType('tar', exporters); + } + static hasDockerExporter(exporters, load) { + return load || Build.hasExporterType('docker', exporters); + } + static hasExporterType(name, exporters) { + const records = (0, sync_1.parse)(exporters.join(`\n`), { + delimiter: ',', + trim: true, + columns: false, + relaxColumnCount: true + }); + for (const record of records) { + if (record.length == 1 && !record[0].startsWith('type=')) { + // Local if no type is defined + // https://github.com/docker/buildx/blob/d2bf42f8b4784d83fde17acb3ed84703ddc2156b/build/output.go#L29-L43 + return name == 'local'; + } + for (const [key, value] of record.map(chunk => chunk.split('=').map(item => item.trim()))) { + if (key == 'type' && value == name) { + return true; + } + } + } + return false; + } + static hasAttestationType(name, attrs) { + const records = (0, sync_1.parse)(attrs, { + delimiter: ',', + trim: true, + columns: false, + relaxColumnCount: true + }); + for (const record of records) { + for (const [key, value] of record.map((chunk) => chunk.split('=').map(item => item.trim()))) { + if (key == 'type' && value == name) { + return true; + } + } + } + return false; + } + static resolveAttestationAttrs(attrs) { + const records = (0, sync_1.parse)(attrs, { + delimiter: ',', + trim: true, + columns: false, + relaxColumnCount: true + }); + const res = []; + for (const record of records) { + for (const attr of record) { + try { + // https://github.com/docker/buildx/blob/8abef5908705e49f7ba88ef8c957e1127b597a2a/util/buildflags/attests.go#L13-L21 + const v = util_1.Util.parseBool(attr); + res.push(`disabled=${!v}`); + } + catch (err) { + res.push(attr); + } + } + } + return res.join(','); + } + static hasGitAuthTokenSecret(secrets) { + for (const secret of secrets) { + if (secret.startsWith('GIT_AUTH_TOKEN=')) { + return true; + } + } + return false; + } + static parseSecretKvp(kvp) { + const delimiterIndex = kvp.indexOf('='); + const key = kvp.substring(0, delimiterIndex); + const value = kvp.substring(delimiterIndex + 1); + if (key.length == 0 || value.length == 0) { + throw new Error(`${kvp} is not a valid secret`); + } + return [key, value]; + } +} +exports.Build = Build; +//# sourceMappingURL=build.js.map \ No newline at end of file diff --git a/lib/buildx/build.js.map b/lib/buildx/build.js.map new file mode 100644 index 00000000..6d9b6296 --- /dev/null +++ b/lib/buildx/build.js.map @@ -0,0 +1 @@ +{"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/buildx/build.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,4CAAoB;AACpB,gDAAwB;AACxB,oDAAsC;AACtC,yCAAqC;AAErC,qCAAgC;AAChC,wCAAmC;AACnC,sCAAiC;AACjC,kCAA6B;AAS7B,MAAa,KAAK;IAKhB,YAAY,IAAgB;QAC1B,IAAI,CAAC,MAAM,GAAG,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,KAAI,IAAI,eAAM,EAAE,CAAC;QAC3C,IAAI,CAAC,WAAW,GAAG,iBAAiB,WAAI,CAAC,oBAAoB,EAAE,MAAM,CAAC;QACtE,IAAI,CAAC,g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,iBAAiB,CAAC,EAAE,CAAC;gBACzC,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,GAAW;QACvC,MAAM,cAAc,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QACxC,MAAM,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC;QAC7C,MAAM,KAAK,GAAG,GAAG,CAAC,SAAS,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC;QAChD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YACzC,MAAM,IAAI,KAAK,CAAC,GAAG,GAAG,wBAAwB,CAAC,CAAC;QAClD,CAAC;QACD,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACtB,CAAC;CACF;AAlRD,sBAkRC"} \ No newline at end of file diff --git a/lib/buildx/builder.d.ts b/lib/buildx/builder.d.ts new file mode 100644 index 00000000..52e071e8 --- /dev/null +++ b/lib/buildx/builder.d.ts @@ -0,0 +1,27 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Buildx } from './buildx'; +import { BuilderInfo } from '../types/buildx/builder'; +export interface BuilderOpts { + buildx?: Buildx; +} +export declare class Builder { + private readonly buildx; + constructor(opts?: BuilderOpts); + exists(name: string): Promise; + inspect(name?: string): Promise; + static parseInspect(data: string): BuilderInfo; +} diff --git a/lib/buildx/builder.js b/lib/buildx/builder.js new file mode 100644 index 00000000..b72030c0 --- /dev/null +++ b/lib/buildx/builder.js @@ -0,0 +1,253 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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.Builder = void 0; +const core = __importStar(require("@actions/core")); +const buildx_1 = require("./buildx"); +const exec_1 = require("../exec"); +class Builder { + constructor(opts) { + this.buildx = (opts === null || opts === void 0 ? void 0 : opts.buildx) || new buildx_1.Buildx(); + } + exists(name) { + return __awaiter(this, void 0, void 0, function* () { + const cmd = yield this.buildx.getCommand(['inspect', name]); + const ok = yield exec_1.Exec.getExecOutput(cmd.command, cmd.args, { + ignoreReturnCode: true, + silent: true + }) + .then(res => { + if (res.stderr.length > 0 && res.exitCode != 0) { + core.debug(`Builder.exists cmd err: ${res.stderr.trim()}`); + return false; + } + return res.exitCode == 0; + }) + .catch(error => { + core.debug(`Builder.exists error: ${error}`); + return false; + }); + core.debug(`Builder.exists: ${ok}`); + return ok; + }); + } + inspect(name) { + return __awaiter(this, void 0, void 0, function* () { + // always enable debug for inspect command, so we can display additional + // fields such as features: https://github.com/docker/buildx/pull/1854 + const envs = Object.assign({}, process.env, { + DEBUG: '1' + }); + const args = ['inspect']; + if (name) { + args.push(name); + } + const cmd = yield this.buildx.getCommand(args); + return yield exec_1.Exec.getExecOutput(cmd.command, cmd.args, { + ignoreReturnCode: true, + silent: true, + env: envs + }).then(res => { + if (res.stderr.length > 0 && res.exitCode != 0) { + throw new Error(res.stderr.trim()); + } + return Builder.parseInspect(res.stdout); + }); + }); + } + static parseInspect(data) { + const builder = { + nodes: [] + }; + let parsingType; + let currentNode = {}; + let currentGCPolicy; + for (const line of data.trim().split(`\n`)) { + const [key, ...rest] = line.split(':'); + const lkey = key.toLowerCase(); + const value = rest.map(v => v.trim()).join(':'); + if (key.length == 0) { + continue; + } + switch (true) { + case lkey == 'name': + parsingType = undefined; + if (builder.name == undefined) { + builder.name = value; + } + else { + if (currentGCPolicy && currentNode.gcPolicy) { + currentNode.gcPolicy.push(currentGCPolicy); + currentGCPolicy = undefined; + } + if (currentNode.name) { + builder.nodes.push(currentNode); + } + currentNode = { name: value }; + } + break; + case lkey == 'driver': + parsingType = undefined; + builder.driver = value; + break; + case lkey == 'last activity': + parsingType = undefined; + builder.lastActivity = new Date(value); + break; + case lkey == 'endpoint': + parsingType = undefined; + currentNode.endpoint = value; + break; + case lkey == 'driver options': + parsingType = undefined; + currentNode['driver-opts'] = (value.match(/([a-zA-Z0-9_.]+)="([^"]*)"/g) || []).map(v => v.replace(/^(.*)="(.*)"$/g, '$1=$2')); + break; + case lkey == 'status': + parsingType = undefined; + currentNode.status = value; + break; + case lkey == 'buildkit daemon flags': + case lkey == 'flags': // buildx < v0.13 + parsingType = undefined; + currentNode['buildkitd-flags'] = value; + break; + case lkey == 'buildkit version': + case lkey == 'buildkit': // buildx < v0.13 + parsingType = undefined; + currentNode.buildkit = value; + break; + case lkey == 'platforms': { + parsingType = undefined; + if (!value) { + break; + } + let platforms = []; + // if a preferred platform is being set then use only these + // https://docs.docker.com/engine/reference/commandline/buildx_inspect/#get-information-about-a-builder-instance + if (value.includes('*')) { + for (const platform of value.split(', ')) { + if (platform.includes('*')) { + platforms.push(platform.replace(/\*/g, '')); + } + } + } + else { + // otherwise set all platforms available + platforms = value.split(', '); + } + currentNode.platforms = platforms.join(','); + break; + } + case lkey == 'features': + parsingType = 'features'; + currentNode.features = {}; + break; + case lkey == 'labels': + parsingType = 'label'; + currentNode.labels = {}; + break; + case lkey.startsWith('gc policy rule#'): + parsingType = 'gcpolicy'; + if (currentNode.gcPolicy && currentGCPolicy) { + currentNode.gcPolicy.push(currentGCPolicy); + currentGCPolicy = undefined; + } + break; + default: { + switch (parsingType || '') { + case 'features': { + currentNode.features = currentNode.features || {}; + currentNode.features[key.trim()] = Boolean(value); + break; + } + case 'label': { + currentNode.labels = currentNode.labels || {}; + currentNode.labels[key.trim()] = value; + break; + } + case 'gcpolicy': { + currentNode.gcPolicy = currentNode.gcPolicy || []; + currentGCPolicy = currentGCPolicy || {}; + switch (lkey.trim()) { + case 'all': { + currentGCPolicy.all = value == 'true'; + break; + } + case 'filters': { + if (value) { + currentGCPolicy.filter = value.split(','); + } + break; + } + case 'keep duration': { + currentGCPolicy.keepDuration = value; + break; + } + case 'keep bytes': { + currentGCPolicy.keepBytes = value; + break; + } + } + break; + } + } + } + } + } + if (currentGCPolicy && currentNode.gcPolicy) { + currentNode.gcPolicy.push(currentGCPolicy); + } + if (currentNode.name) { + builder.nodes.push(currentNode); + } + return builder; + } +} +exports.Builder = Builder; +//# sourceMappingURL=builder.js.map \ No newline at end of file diff --git a/lib/buildx/builder.js.map b/lib/buildx/builder.js.map new file mode 100644 index 00000000..27be40f8 --- /dev/null +++ b/lib/buildx/builder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../src/buildx/builder.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAAsC;AAEtC,qCAAgC;AAChC,kCAA6B;AAQ7B,MAAa,OAAO;IAGlB,YAAY,IAAkB;QAC5B,IAAI,CAAC,MAAM,GAAG,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,KAAI,IAAI,eAAM,EAAE,CAAC;IAC7C,CAAC;IAEY,MAAM,CAAC,IAAY;;YAC9B,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;YAE5D,MAAM,EAAE,GAAY,MAAM,WAAI,CAAC,aAAa,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,IAAI,EAAE;gBAClE,gBAAgB,EAAE,IAAI;gBACtB,MAAM,EAAE,IAAI;aACb,CAAC;iBACC,IAAI,CAAC,GAAG,CAAC,EAAE;gBACV,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,GAAG,CAAC,QAAQ,IAAI,CAAC,EAAE,CAAC;oBAC/C,IAAI,CAAC,KAAK,CAAC,2BAA2B,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;oBAC3D,OAAO,KAA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ACH,CAAC;YACH,CAAC;QACH,CAAC;QACD,IAAI,eAAe,IAAI,WAAW,CAAC,QAAQ,EAAE,CAAC;YAC5C,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QAC7C,CAAC;QACD,IAAI,WAAW,CAAC,IAAI,EAAE,CAAC;YACrB,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAClC,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF;AA1MD,0BA0MC"} \ No newline at end of file diff --git a/lib/buildx/buildx.d.ts b/lib/buildx/buildx.d.ts new file mode 100644 index 00000000..ae9e4982 --- /dev/null +++ b/lib/buildx/buildx.d.ts @@ -0,0 +1,42 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Cert, LocalRefsOpts, LocalRefsResponse } from '../types/buildx/buildx'; +export interface BuildxOpts { + standalone?: boolean; +} +export declare class Buildx { + private _version; + private _versionOnce; + private readonly _standalone; + static readonly containerNamePrefix = "buildx_buildkit_"; + constructor(opts?: BuildxOpts); + static get configDir(): string; + static get refsDir(): string; + static get refsGroupDir(): string; + static get certsDir(): string; + isStandalone(): Promise; + getCommand(args: Array): Promise<{ + command: string; + args: string[]; + }>; + isAvailable(): Promise; + version(): Promise; + printVersion(): Promise; + static parseVersion(stdout: string): string; + versionSatisfies(range: string, version?: string): Promise; + static resolveCertsDriverOpts(driver: string, endpoint: string, cert: Cert): Array; + static refs(opts: LocalRefsOpts, refs?: LocalRefsResponse): LocalRefsResponse; +} diff --git a/lib/buildx/buildx.js b/lib/buildx/buildx.js new file mode 100644 index 00000000..e58a91c1 --- /dev/null +++ b/lib/buildx/buildx.js @@ -0,0 +1,245 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Buildx = void 0; +const fs_1 = __importDefault(require("fs")); +const path_1 = __importDefault(require("path")); +const core = __importStar(require("@actions/core")); +const semver = __importStar(require("semver")); +const docker_1 = require("../docker/docker"); +const exec_1 = require("../exec"); +class Buildx { + constructor(opts) { + this._standalone = opts === null || opts === void 0 ? void 0 : opts.standalone; + this._version = ''; + this._versionOnce = false; + } + static get configDir() { + return process.env.BUILDX_CONFIG || path_1.default.join(docker_1.Docker.configDir, 'buildx'); + } + static get refsDir() { + return path_1.default.join(Buildx.configDir, 'refs'); + } + static get refsGroupDir() { + return path_1.default.join(Buildx.refsDir, '__group__'); + } + static get certsDir() { + return path_1.default.join(Buildx.configDir, 'certs'); + } + isStandalone() { + return __awaiter(this, void 0, void 0, function* () { + var _a; + const standalone = (_a = this._standalone) !== null && _a !== void 0 ? _a : !(yield docker_1.Docker.isAvailable()); + core.debug(`Buildx.isStandalone: ${standalone}`); + return standalone; + }); + } + getCommand(args) { + return __awaiter(this, void 0, void 0, function* () { + const standalone = yield this.isStandalone(); + return { + command: standalone ? 'buildx' : 'docker', + args: standalone ? args : ['buildx', ...args] + }; + }); + } + isAvailable() { + return __awaiter(this, void 0, void 0, function* () { + const cmd = yield this.getCommand([]); + const ok = yield exec_1.Exec.getExecOutput(cmd.command, cmd.args, { + ignoreReturnCode: true, + silent: true + }) + .then(res => { + if (res.stderr.length > 0 && res.exitCode != 0) { + core.debug(`Buildx.isAvailable cmd err: ${res.stderr.trim()}`); + return false; + } + return res.exitCode == 0; + }) + .catch(error => { + core.debug(`Buildx.isAvailable error: ${error}`); + return false; + }); + core.debug(`Buildx.isAvailable: ${ok}`); + return ok; + }); + } + version() { + return __awaiter(this, void 0, void 0, function* () { + if (this._versionOnce) { + return this._version; + } + this._versionOnce = true; + const cmd = yield this.getCommand(['version']); + this._version = yield exec_1.Exec.getExecOutput(cmd.command, cmd.args, { + ignoreReturnCode: true, + silent: true + }).then(res => { + if (res.stderr.length > 0 && res.exitCode != 0) { + throw new Error(res.stderr.trim()); + } + return Buildx.parseVersion(res.stdout.trim()); + }); + return this._version; + }); + } + printVersion() { + return __awaiter(this, void 0, void 0, function* () { + const cmd = yield this.getCommand(['version']); + yield exec_1.Exec.exec(cmd.command, cmd.args, { + failOnStdErr: false + }); + }); + } + static parseVersion(stdout) { + const matches = /\sv?([0-9a-f]{7}|[0-9.]+)/.exec(stdout); + if (!matches) { + throw new Error(`Cannot parse buildx version`); + } + return matches[1]; + } + versionSatisfies(range, version) { + return __awaiter(this, void 0, void 0, function* () { + const ver = version !== null && version !== void 0 ? version : (yield this.version()); + if (!ver) { + core.debug(`Buildx.versionSatisfies false: undefined version`); + return false; + } + const res = semver.satisfies(ver, range) || /^[0-9a-f]{7}$/.exec(ver) !== null; + core.debug(`Buildx.versionSatisfies ${ver} statisfies ${range}: ${res}`); + return res; + }); + } + static resolveCertsDriverOpts(driver, endpoint, cert) { + let url; + try { + url = new URL(endpoint); + } + catch (e) { + return []; + } + if (url.protocol != 'tcp:') { + return []; + } + const driverOpts = []; + if (Object.keys(cert).length == 0) { + return driverOpts; + } + let host = url.hostname; + if (url.port.length > 0) { + host += `-${url.port}`; + } + if (cert.cacert !== undefined) { + const cacertpath = path_1.default.join(Buildx.certsDir, `cacert_${host}.pem`); + fs_1.default.writeFileSync(cacertpath, cert.cacert); + driverOpts.push(`cacert=${cacertpath}`); + } + if (cert.cert !== undefined) { + const certpath = path_1.default.join(Buildx.certsDir, `cert_${host}.pem`); + fs_1.default.writeFileSync(certpath, cert.cert); + driverOpts.push(`cert=${certpath}`); + } + if (cert.key !== undefined) { + const keypath = path_1.default.join(Buildx.certsDir, `key_${host}.pem`); + fs_1.default.writeFileSync(keypath, cert.key); + driverOpts.push(`key=${keypath}`); + } + if (driver != 'remote') { + return []; + } + return driverOpts; + } + static refs(opts, refs = {}) { + const { dir, builderName, nodeName, since } = opts; + let dirpath = path_1.default.resolve(dir); + if (opts.builderName) { + dirpath = path_1.default.join(dirpath, opts.builderName); + } + if (opts.nodeName) { + dirpath = path_1.default.join(dirpath, opts.nodeName); + } + if (!fs_1.default.existsSync(dirpath)) { + return refs; + } + const files = fs_1.default.readdirSync(dirpath); + for (const file of files) { + const filePath = path_1.default.join(dirpath, file); + const stat = fs_1.default.statSync(filePath); + if (stat.isDirectory()) { + const nopts = Object.assign({}, opts); + if (!builderName) { + if (file === '__group__') { + continue; + } + nopts.builderName = file; + } + else if (!nodeName) { + nopts.nodeName = file; + } + Buildx.refs(nopts, refs); + } + else { + if (since && stat.mtime < since) { + continue; + } + const localState = JSON.parse(fs_1.default.readFileSync(filePath, 'utf8')); + const ref = `${builderName}/${nodeName}/${file}`; + refs[ref] = localState; + } + } + return refs; + } +} +exports.Buildx = Buildx; +Buildx.containerNamePrefix = 'buildx_buildkit_'; +//# sourceMappingURL=buildx.js.map \ No newline at end of file diff --git a/lib/buildx/buildx.js.map b/lib/buildx/buildx.js.map new file mode 100644 index 00000000..ec8144e0 --- /dev/null +++ b/lib/buildx/buildx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buildx.js","sourceRoot":"","sources":["../../src/buildx/buildx.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,4CAAoB;AACpB,gDAAwB;AACxB,oDAAsC;AACtC,+CAAiC;AAEjC,6CAAwC;AACxC,kCAA6B;AAQ7B,MAAa,MAAM;IAOjB,YAAY,IAAiB;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,UAAU,CAAC;QACpC,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;IAC5B,CAAC;IAED,MAAM,KAAK,SAAS;QAClB,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,cAAI,CAAC,IAAI,CAAC,eAAM,CAAC,S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C,IAAI,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;gBACvB,MAAM,KAAK,qBAAsB,IAAI,CAAC,CAAC;gBACvC,IAAI,CAAC,WAAW,EAAE,CAAC;oBACjB,IAAI,IAAI,KAAK,WAAW,EAAE,CAAC;wBACzB,SAAS;oBACX,CAAC;oBACD,KAAK,CAAC,WAAW,GAAG,IAAI,CAAC;gBAC3B,CAAC;qBAAM,IAAI,CAAC,QAAQ,EAAE,CAAC;oBACrB,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;gBACxB,CAAC;gBACD,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YAC3B,CAAC;iBAAM,CAAC;gBACN,IAAI,KAAK,IAAI,IAAI,CAAC,KAAK,GAAG,KAAK,EAAE,CAAC;oBAChC,SAAS;gBACX,CAAC;gBACD,MAAM,UAAU,GAAe,IAAI,CAAC,KAAK,CAAC,YAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC;gBAC7E,MAAM,GAAG,GAAG,GAAG,WAAW,IAAI,QAAQ,IAAI,IAAI,EAAE,CAAC;gBACjD,IAAI,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC;YACzB,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;;AA7LH,wBA8LC;AAzLwB,0BAAmB,GAAG,kBAAkB,CAAC"} \ No newline at end of file diff --git a/lib/buildx/history.d.ts b/lib/buildx/history.d.ts new file mode 100644 index 00000000..41190622 --- /dev/null +++ b/lib/buildx/history.d.ts @@ -0,0 +1,27 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Buildx } from './buildx'; +import { ExportRecordOpts, ExportRecordResponse } from '../types/buildx/history'; +export interface HistoryOpts { + buildx?: Buildx; +} +export declare class History { + private readonly buildx; + private static readonly EXPORT_TOOL_IMAGE; + constructor(opts?: HistoryOpts); + export(opts: ExportRecordOpts): Promise; + private static spawn; +} diff --git a/lib/buildx/history.js b/lib/buildx/history.js new file mode 100644 index 00000000..9b19c4fd --- /dev/null +++ b/lib/buildx/history.js @@ -0,0 +1,186 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.History = void 0; +const child_process_1 = require("child_process"); +const fs_1 = __importDefault(require("fs")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +const core = __importStar(require("@actions/core")); +const buildx_1 = require("./buildx"); +const context_1 = require("../context"); +const docker_1 = require("../docker/docker"); +const exec_1 = require("../exec"); +const github_1 = require("../github"); +class History { + constructor(opts) { + this.buildx = (opts === null || opts === void 0 ? void 0 : opts.buildx) || new buildx_1.Buildx(); + } + export(opts) { + return __awaiter(this, void 0, void 0, function* () { + if (os_1.default.platform() === 'win32') { + throw new Error('Exporting a build record is currently not supported on Windows'); + } + if (!(yield docker_1.Docker.isAvailable())) { + throw new Error('Docker is required to export a build record'); + } + let builderName = ''; + let nodeName = ''; + const refs = []; + for (const ref of opts.refs) { + const refParts = ref.split('/'); + if (refParts.length != 3) { + throw new Error(`Invalid build ref: ${ref}`); + } + refs.push(refParts[2]); + // Set builder name and node name from the first ref if not already set. + // We assume all refs are from the same builder and node. + if (!builderName) { + builderName = refParts[0]; + } + if (!nodeName) { + nodeName = refParts[1]; + } + } + if (refs.length === 0) { + throw new Error('No build refs provided'); + } + const outDir = path_1.default.join(context_1.Context.tmpDir(), 'export'); + core.info(`exporting build record to ${outDir}`); + fs_1.default.mkdirSync(outDir, { recursive: true }); + const buildxInFifoPath = context_1.Context.tmpName({ + template: 'buildx-in-XXXXXX.fifo', + tmpdir: context_1.Context.tmpDir() + }); + yield exec_1.Exec.exec('mkfifo', [buildxInFifoPath]); + const buildxOutFifoPath = context_1.Context.tmpName({ + template: 'buildx-out-XXXXXX.fifo', + tmpdir: context_1.Context.tmpDir() + }); + yield exec_1.Exec.exec('mkfifo', [buildxOutFifoPath]); + const buildxCmd = yield this.buildx.getCommand(['--builder', builderName, 'dial-stdio']); + const buildxDialStdioProc = History.spawn(buildxCmd.command, buildxCmd.args); + fs_1.default.createReadStream(buildxInFifoPath).pipe(buildxDialStdioProc.stdin); + buildxDialStdioProc.stdout.pipe(fs_1.default.createWriteStream(buildxOutFifoPath)); + const tmpDockerbuildFilename = path_1.default.join(outDir, 'rec.dockerbuild'); + const summaryFilename = path_1.default.join(outDir, 'summary.json'); + yield new Promise((resolve, reject) => { + const ebargs = ['--ref-state-dir=/buildx-refs', `--node=${builderName}/${nodeName}`]; + for (const ref of refs) { + ebargs.push(`--ref=${ref}`); + } + if (typeof process.getuid === 'function') { + ebargs.push(`--uid=${process.getuid()}`); + } + if (typeof process.getgid === 'function') { + ebargs.push(`--gid=${process.getgid()}`); + } + // prettier-ignore + const dockerRunProc = History.spawn('docker', [ + 'run', '--rm', '-i', + '-v', `${buildx_1.Buildx.refsDir}:/buildx-refs`, + '-v', `${outDir}:/out`, + opts.image || History.EXPORT_TOOL_IMAGE, + ...ebargs + ]); + fs_1.default.createReadStream(buildxOutFifoPath).pipe(dockerRunProc.stdin); + dockerRunProc.stdout.pipe(fs_1.default.createWriteStream(buildxInFifoPath)); + dockerRunProc.on('close', code => { + if (code === 0) { + if (!fs_1.default.existsSync(tmpDockerbuildFilename)) { + reject(new Error(`Failed to export build record: ${tmpDockerbuildFilename} not found`)); + } + else { + resolve(); + } + } + else { + reject(new Error(`Process "docker run" exited with code ${code}`)); + } + }); + dockerRunProc.on('error', err => { + core.error(`Error executing buildx dial-stdio: ${err}`); + reject(err); + }); + }).catch(err => { + throw err; + }); + let dockerbuildFilename = `${github_1.GitHub.context.repo.owner}~${github_1.GitHub.context.repo.repo}~${refs[0].substring(0, 6).toUpperCase()}`; + if (refs.length > 1) { + dockerbuildFilename += `+${refs.length - 1}`; + } + const dockerbuildPath = path_1.default.join(outDir, `${dockerbuildFilename}.dockerbuild`); + fs_1.default.renameSync(tmpDockerbuildFilename, dockerbuildPath); + const dockerbuildStats = fs_1.default.statSync(dockerbuildPath); + core.info(`Parsing ${summaryFilename}`); + fs_1.default.statSync(summaryFilename); + const summaries = JSON.parse(fs_1.default.readFileSync(summaryFilename, { encoding: 'utf-8' })); + return { + dockerbuildFilename: dockerbuildPath, + dockerbuildSize: dockerbuildStats.size, + summaries: summaries, + builderName: builderName, + nodeName: nodeName, + refs: refs + }; + }); + } + static spawn(command, args) { + core.info(`[command]${command}${args ? ` ${args.join(' ')}` : ''}`); + return (0, child_process_1.spawn)(command, args || [], { + stdio: ['pipe', 'pipe', 'inherit'] + }); + } +} +exports.History = History; +History.EXPORT_TOOL_IMAGE = 'docker.io/dockereng/export-build:latest'; +//# sourceMappingURL=history.js.map \ No newline at end of file diff --git a/lib/buildx/history.js.map b/lib/buildx/history.js.map new file mode 100644 index 00000000..4624ad7c --- /dev/null +++ b/lib/buildx/history.js.map @@ -0,0 +1 @@ +{"version":3,"file":"history.js","sourceRoot":"","sources":["../../src/buildx/history.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,iDAAyD;AACzD,4CAAoB;AAEpB,4CAAoB;AACpB,gDAAwB;AACxB,oDAAsC;AAEtC,qCAAgC;AAChC,wCAAmC;AACnC,6CAAwC;AACxC,kCAA6B;AAC7B,sCAAiC;AAQjC,MAAa,OAAO;IAKlB,YAAY,IAAkB;QAC5B,IAAI,CAAC,MAAM,GAAG,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,KAAI,IAAI,eAAM,EAAE,CAAC;IAC7C,CAAC;IAEY,MAAM,CAAC,IAAsB;;YACxC,IAAI,YAAE,CAAC,QAAQ,EAAE,KAAK,OAAO,EAAE,CAAC;gBAC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AAC;YAE/F,OAAO;gBACL,mBAAmB,EAAE,eAAe;gBACpC,eAAe,EAAE,gBAAgB,CAAC,IAAI;gBACtC,SAAS,EAAE,SAAS;gBACpB,WAAW,EAAE,WAAW;gBACxB,QAAQ,EAAE,QAAQ;gBAClB,IAAI,EAAE,IAAI;aACX,CAAC;QACJ,CAAC;KAAA;IAEO,MAAM,CAAC,KAAK,CAAC,OAAe,EAAE,IAA4B;QAChE,IAAI,CAAC,IAAI,CAAC,YAAY,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACpE,OAAO,IAAA,qBAAK,EAAC,OAAO,EAAE,IAAI,IAAI,EAAE,EAAE;YAChC,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC;SACnC,CAAC,CAAC;IACL,CAAC;;AApIH,0BAqIC;AAlIyB,yBAAiB,GAAW,yCAAyC,CAAC"} \ No newline at end of file diff --git a/lib/buildx/install.d.ts b/lib/buildx/install.d.ts new file mode 100644 index 00000000..d48657b4 --- /dev/null +++ b/lib/buildx/install.d.ts @@ -0,0 +1,34 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DownloadVersion } from '../types/buildx/buildx'; +import { GitHubRelease } from '../types/github'; +export interface InstallOpts { + standalone?: boolean; +} +export declare class Install { + private readonly _standalone; + constructor(opts?: InstallOpts); + download(v: string, ghaNoCache?: boolean): Promise; + build(gitContext: string, ghaNoCache?: boolean): Promise; + installStandalone(binPath: string, dest?: string): Promise; + installPlugin(binPath: string, dest?: string): Promise; + private buildCommand; + private isStandalone; + private filename; + private vspec; + static getDownloadVersion(v: string): Promise; + static getRelease(version: DownloadVersion): Promise; +} diff --git a/lib/buildx/install.js b/lib/buildx/install.js new file mode 100644 index 00000000..f2f28b40 --- /dev/null +++ b/lib/buildx/install.js @@ -0,0 +1,333 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Install = void 0; +const fs_1 = __importDefault(require("fs")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +const core = __importStar(require("@actions/core")); +const httpm = __importStar(require("@actions/http-client")); +const tc = __importStar(require("@actions/tool-cache")); +const semver = __importStar(require("semver")); +const util = __importStar(require("util")); +const buildx_1 = require("./buildx"); +const cache_1 = require("../cache"); +const context_1 = require("../context"); +const exec_1 = require("../exec"); +const docker_1 = require("../docker/docker"); +const git_1 = require("../git"); +const util_1 = require("../util"); +class Install { + constructor(opts) { + this._standalone = opts === null || opts === void 0 ? void 0 : opts.standalone; + } + /* + * Download buildx binary from GitHub release + * @param v: version semver version or latest + * @param ghaNoCache: disable binary caching in GitHub Actions cache backend + * @returns path to the buildx binary + */ + download(v, ghaNoCache) { + return __awaiter(this, void 0, void 0, function* () { + const version = yield Install.getDownloadVersion(v); + core.debug(`Install.download version: ${version.version}`); + const release = yield Install.getRelease(version); + core.debug(`Install.download release tag name: ${release.tag_name}`); + const vspec = yield this.vspec(release.tag_name); + core.debug(`Install.download vspec: ${vspec}`); + const c = semver.clean(vspec) || ''; + if (!semver.valid(c)) { + throw new Error(`Invalid Buildx version "${vspec}".`); + } + const installCache = new cache_1.Cache({ + htcName: version.key != 'official' ? `buildx-dl-bin-${version.key}` : 'buildx-dl-bin', + htcVersion: vspec, + baseCacheDir: path_1.default.join(buildx_1.Buildx.configDir, '.bin'), + cacheFile: os_1.default.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx', + ghaNoCache: ghaNoCache + }); + const cacheFoundPath = yield installCache.find(); + if (cacheFoundPath) { + core.info(`Buildx binary found in ${cacheFoundPath}`); + return cacheFoundPath; + } + const downloadURL = util.format(version.downloadURL, vspec, this.filename(vspec)); + core.info(`Downloading ${downloadURL}`); + const htcDownloadPath = yield tc.downloadTool(downloadURL); + core.debug(`Install.download htcDownloadPath: ${htcDownloadPath}`); + const cacheSavePath = yield installCache.save(htcDownloadPath); + core.info(`Cached to ${cacheSavePath}`); + return cacheSavePath; + }); + } + /* + * Build buildx binary from source + * @param gitContext: git repo context + * @param ghaNoCache: disable binary caching in GitHub Actions cache backend + * @returns path to the buildx binary + */ + build(gitContext, ghaNoCache) { + return __awaiter(this, void 0, void 0, function* () { + const vspec = yield this.vspec(gitContext); + core.debug(`Install.build vspec: ${vspec}`); + const installCache = new cache_1.Cache({ + htcName: 'buildx-build-bin', + htcVersion: vspec, + baseCacheDir: path_1.default.join(buildx_1.Buildx.configDir, '.bin'), + cacheFile: os_1.default.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx', + ghaNoCache: ghaNoCache + }); + const cacheFoundPath = yield installCache.find(); + if (cacheFoundPath) { + core.info(`Buildx binary found in ${cacheFoundPath}`); + return cacheFoundPath; + } + const outputDir = path_1.default.join(context_1.Context.tmpDir(), 'buildx-build-cache'); + const buildCmd = yield this.buildCommand(gitContext, outputDir); + const buildBinPath = yield exec_1.Exec.getExecOutput(buildCmd.command, buildCmd.args, { + ignoreReturnCode: true + }).then(res => { + var _a, _b, _c; + if (res.stderr.length > 0 && res.exitCode != 0) { + throw new Error(`build failed with: ${(_c = (_b = (_a = res.stderr.match(/(.*)\s*$/)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : 'unknown error'}`); + } + return `${outputDir}/buildx`; + }); + const cacheSavePath = yield installCache.save(buildBinPath); + core.info(`Cached to ${cacheSavePath}`); + return cacheSavePath; + }); + } + installStandalone(binPath, dest) { + return __awaiter(this, void 0, void 0, function* () { + core.info('Standalone mode'); + dest = dest || context_1.Context.tmpDir(); + const binDir = path_1.default.join(dest, 'buildx-bin-standalone'); + if (!fs_1.default.existsSync(binDir)) { + fs_1.default.mkdirSync(binDir, { recursive: true }); + } + const binName = os_1.default.platform() == 'win32' ? 'buildx.exe' : 'buildx'; + const buildxPath = path_1.default.join(binDir, binName); + fs_1.default.copyFileSync(binPath, buildxPath); + core.info('Fixing perms'); + fs_1.default.chmodSync(buildxPath, '0755'); + core.addPath(binDir); + core.info('Added Buildx to PATH'); + core.info(`Binary path: ${buildxPath}`); + return buildxPath; + }); + } + installPlugin(binPath, dest) { + return __awaiter(this, void 0, void 0, function* () { + core.info('Docker plugin mode'); + dest = dest || docker_1.Docker.configDir; + const pluginsDir = path_1.default.join(dest, 'cli-plugins'); + if (!fs_1.default.existsSync(pluginsDir)) { + fs_1.default.mkdirSync(pluginsDir, { recursive: true }); + } + const binName = os_1.default.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx'; + const pluginPath = path_1.default.join(pluginsDir, binName); + fs_1.default.copyFileSync(binPath, pluginPath); + core.info('Fixing perms'); + fs_1.default.chmodSync(pluginPath, '0755'); + core.info(`Plugin path: ${pluginPath}`); + return pluginPath; + }); + } + buildCommand(gitContext, outputDir) { + return __awaiter(this, void 0, void 0, function* () { + const buildxStandaloneFound = yield new buildx_1.Buildx({ standalone: true }).isAvailable(); + const buildxPluginFound = yield new buildx_1.Buildx({ standalone: false }).isAvailable(); + let buildStandalone = false; + if ((yield this.isStandalone()) && buildxStandaloneFound) { + core.debug(`Install.buildCommand: Buildx standalone found, build with it`); + buildStandalone = true; + } + else if (!(yield this.isStandalone()) && buildxPluginFound) { + core.debug(`Install.buildCommand: Buildx plugin found, build with it`); + buildStandalone = false; + } + else if (buildxStandaloneFound) { + core.debug(`Install.buildCommand: Buildx plugin not found, but standalone found so trying to build with it`); + buildStandalone = true; + } + else if (buildxPluginFound) { + core.debug(`Install.buildCommand: Buildx standalone not found, but plugin found so trying to build with it`); + buildStandalone = false; + } + else { + throw new Error(`Neither buildx standalone or plugin have been found to build from ref ${gitContext}`); + } + const args = ['build', '--target', 'binaries', '--platform', 'local', '--build-arg', 'BUILDKIT_CONTEXT_KEEP_GIT_DIR=1', '--output', `type=local,dest=${outputDir}`]; + if (process.env.GIT_AUTH_TOKEN) { + args.push('--secret', 'id=GIT_AUTH_TOKEN'); + } + args.push(gitContext); + //prettier-ignore + return yield new buildx_1.Buildx({ standalone: buildStandalone }).getCommand(args); + }); + } + isStandalone() { + return __awaiter(this, void 0, void 0, function* () { + var _a; + const standalone = (_a = this._standalone) !== null && _a !== void 0 ? _a : !(yield docker_1.Docker.isAvailable()); + core.debug(`Install.isStandalone: ${standalone}`); + return standalone; + }); + } + filename(version) { + let arch; + switch (os_1.default.arch()) { + case 'x64': { + arch = 'amd64'; + break; + } + case 'ppc64': { + arch = 'ppc64le'; + break; + } + case 'arm': { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const arm_version = process.config.variables.arm_version; + arch = arm_version ? 'arm-v' + arm_version : 'arm'; + break; + } + default: { + arch = os_1.default.arch(); + break; + } + } + const platform = os_1.default.platform() == 'win32' ? 'windows' : os_1.default.platform(); + const ext = os_1.default.platform() == 'win32' ? '.exe' : ''; + return util.format('buildx-v%s.%s-%s%s', version, platform, arch, ext); + } + /* + * Get version spec (fingerprint) for cache key. If versionOrRef is a valid + * Git context, then return the SHA of the ref along the repo and owner and + * create a hash of it. Otherwise, return the versionOrRef (semver) as is + * without the 'v' prefix. + */ + vspec(versionOrRef) { + return __awaiter(this, void 0, void 0, function* () { + if (!util_1.Util.isValidRef(versionOrRef)) { + const v = versionOrRef.replace(/^v+|v+$/g, ''); + core.info(`Use ${v} version spec cache key for ${versionOrRef}`); + return v; + } + // eslint-disable-next-line prefer-const + let [baseURL, ref] = versionOrRef.split('#'); + if (ref.length == 0) { + ref = 'master'; + } + let sha; + if (ref.match(/^[0-9a-fA-F]{40}$/)) { + sha = ref; + } + else { + sha = yield git_1.Git.remoteSha(baseURL, ref, process.env.GIT_AUTH_TOKEN); + } + const [owner, repo] = baseURL.substring('https://github.com/'.length).split('/'); + const key = `${owner}/${util_1.Util.trimSuffix(repo, '.git')}/${sha}`; + const hash = util_1.Util.hash(key); + core.info(`Use ${hash} version spec cache key for ${key}`); + return hash; + }); + } + static getDownloadVersion(v) { + return __awaiter(this, void 0, void 0, function* () { + let [repoKey, version] = v.split(':'); + if (!version) { + version = repoKey; + repoKey = 'official'; + } + switch (repoKey) { + case 'official': { + return { + key: repoKey, + version: version, + downloadURL: 'https://github.com/docker/buildx/releases/download/v%s/%s', + releasesURL: 'https://raw.githubusercontent.com/docker/actions-toolkit/main/.github/buildx-releases.json' + }; + } + case 'lab': { + return { + key: repoKey, + version: version, + downloadURL: 'https://github.com/docker/buildx-desktop/releases/download/v%s/%s', + releasesURL: 'https://raw.githubusercontent.com/docker/actions-toolkit/main/.github/buildx-lab-releases.json' + }; + } + default: { + throw new Error(`Cannot find buildx version for ${v}`); + } + } + }); + } + static getRelease(version) { + return __awaiter(this, void 0, void 0, function* () { + const http = new httpm.HttpClient('docker-actions-toolkit'); + const resp = yield http.get(version.releasesURL); + const body = yield resp.readBody(); + const statusCode = resp.message.statusCode || 500; + if (statusCode >= 400) { + throw new Error(`Failed to get Buildx releases from ${version.releasesURL} with status code ${statusCode}: ${body}`); + } + const releases = JSON.parse(body); + if (!releases[version.version]) { + throw new Error(`Cannot find Buildx release ${version.version} in ${version.releasesURL}`); + } + return releases[version.version]; + }); + } +} +exports.Install = Install; +//# sourceMappingURL=install.js.map \ No newline at end of file diff --git a/lib/buildx/install.js.map b/lib/buildx/install.js.map new file mode 100644 index 00000000..1d0eb906 --- /dev/null +++ b/lib/buildx/install.js.map @@ -0,0 +1 @@ +{"version":3,"file":"install.js","sourceRoot":"","sources":["../../src/buildx/install.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,4CAAoB;AACpB,4CAAoB;AACpB,gDAAwB;AACxB,oDAAsC;AACtC,4DAA8C;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AnRD,0BAmRC"} \ No newline at end of file diff --git a/lib/cache.d.ts b/lib/cache.d.ts new file mode 100644 index 00000000..7e03fa56 --- /dev/null +++ b/lib/cache.d.ts @@ -0,0 +1,40 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface CacheOpts { + htcName: string; + htcVersion: string; + baseCacheDir: string; + cacheFile: string; + ghaNoCache?: boolean; +} +export interface CachePostState { + dir: string; + key: string; +} +export declare class Cache { + private readonly opts; + private readonly ghaCacheKey; + private readonly ghaNoCache?; + private readonly cacheDir; + private readonly cachePath; + private static readonly POST_CACHE_KEY; + constructor(opts: CacheOpts); + save(file: string): Promise; + find(): Promise; + static post(): Promise; + private copyToCache; + private platform; +} diff --git a/lib/cache.js b/lib/cache.js new file mode 100644 index 00000000..6b31d585 --- /dev/null +++ b/lib/cache.js @@ -0,0 +1,148 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Cache = void 0; +const fs_1 = __importDefault(require("fs")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +const core = __importStar(require("@actions/core")); +const tc = __importStar(require("@actions/tool-cache")); +const cache = __importStar(require("@actions/cache")); +const util = __importStar(require("util")); +class Cache { + constructor(opts) { + this.opts = opts; + this.ghaCacheKey = util.format('%s-%s-%s', this.opts.htcName, this.opts.htcVersion, this.platform()); + this.ghaNoCache = this.opts.ghaNoCache; + this.cacheDir = path_1.default.join(this.opts.baseCacheDir, this.opts.htcVersion, this.platform()); + this.cachePath = path_1.default.join(this.cacheDir, this.opts.cacheFile); + if (!fs_1.default.existsSync(this.cacheDir)) { + fs_1.default.mkdirSync(this.cacheDir, { recursive: true }); + } + } + save(file) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Cache.save ${file}`); + const cachePath = this.copyToCache(file); + const htcPath = yield tc.cacheDir(this.cacheDir, this.opts.htcName, this.opts.htcVersion, this.platform()); + core.debug(`Cache.save cached to hosted tool cache ${htcPath}`); + if (!this.ghaNoCache && cache.isFeatureAvailable()) { + core.debug(`Cache.save sending ${this.ghaCacheKey} to post state`); + core.saveState(Cache.POST_CACHE_KEY, JSON.stringify({ + dir: this.cacheDir, + key: this.ghaCacheKey + })); + } + return cachePath; + }); + } + find() { + return __awaiter(this, void 0, void 0, function* () { + let htcPath = tc.find(this.opts.htcName, this.opts.htcVersion, this.platform()); + if (htcPath) { + core.info(`Restored from hosted tool cache ${htcPath}`); + return this.copyToCache(`${htcPath}/${this.opts.cacheFile}`); + } + if (!this.ghaNoCache && cache.isFeatureAvailable()) { + core.debug(`GitHub Actions cache feature available`); + if (yield cache.restoreCache([this.cacheDir], this.ghaCacheKey)) { + core.info(`Restored ${this.ghaCacheKey} from GitHub Actions cache`); + htcPath = yield tc.cacheDir(this.cacheDir, this.opts.htcName, this.opts.htcVersion, this.platform()); + core.info(`Cached to hosted tool cache ${htcPath}`); + return this.copyToCache(`${htcPath}/${this.opts.cacheFile}`); + } + } + else if (this.ghaNoCache) { + core.info(`GitHub Actions cache disabled`); + } + else { + core.info(`GitHub Actions cache feature not available`); + } + return ''; + }); + } + static post() { + return __awaiter(this, void 0, void 0, function* () { + const state = core.getState(Cache.POST_CACHE_KEY); + if (!state) { + core.info(`State not set`); + return Promise.resolve(undefined); + } + let cacheState; + try { + cacheState = JSON.parse(state); + } + catch (e) { + throw new Error(`Failed to parse cache post state: ${e}`); + } + if (!cacheState.dir || !cacheState.key) { + throw new Error(`Invalid cache post state: ${state}`); + } + core.info(`Caching ${cacheState.key} to GitHub Actions cache`); + yield cache.saveCache([cacheState.dir], cacheState.key); + return cacheState; + }); + } + copyToCache(file) { + core.debug(`Copying ${file} to ${this.cachePath}`); + fs_1.default.copyFileSync(file, this.cachePath); + return this.cachePath; + } + platform() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const arm_version = process.config.variables.arm_version; + return `${os_1.default.platform()}-${os_1.default.arch()}${arm_version ? 'v' + arm_version : ''}`; + } +} +exports.Cache = Cache; +Cache.POST_CACHE_KEY = 'postCache'; +//# sourceMappingURL=cache.js.map \ No newline at end of file diff --git a/lib/cache.js.map b/lib/cache.js.map new file mode 100644 index 00000000..1bbd459e --- /dev/null +++ b/lib/cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.js","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,4CAAoB;AACpB,4CAAoB;AACpB,gDAAwB;AACxB,oDAAsC;AACtC,wDAA0C;AAC1C,sDAAwC;AACxC,2CAA6B;AAe7B,MAAa,KAAK;IAShB,YAAY,IAAe;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;QACrG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC;QACvC,IAAI,CAAC,QAAQ,GAAG,cAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;QACzF,IAAI,CAAC,SAAS,GAAG,cAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC/D,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAClC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/dev/null +++ b/lib/context.d.ts @@ -0,0 +1,25 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as tmp from 'tmp'; +export declare class Context { + private static readonly _tmpDir; + private static ensureDirExists; + static tmpDir(): string; + static tmpName(options?: tmp.TmpNameOptions): string; + static gitRef(): string; + static gitContext(): string; + static provenanceBuilderID(): string; +} diff --git a/lib/context.js b/lib/context.js new file mode 100644 index 00000000..d9a85972 --- /dev/null +++ b/lib/context.js @@ -0,0 +1,81 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Context = void 0; +const fs_1 = __importDefault(require("fs")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +const tmp = __importStar(require("tmp")); +const github = __importStar(require("@actions/github")); +const github_1 = require("./github"); +class Context { + static ensureDirExists(dir) { + fs_1.default.mkdirSync(dir, { recursive: true }); + return dir; + } + static tmpDir() { + return Context._tmpDir; + } + static tmpName(options) { + return tmp.tmpNameSync(options); + } + static gitRef() { + let gitRef = github.context.ref; + if (github.context.sha && gitRef && !gitRef.startsWith('refs/')) { + gitRef = `refs/heads/${github.context.ref}`; + } + if (github.context.sha && !gitRef.startsWith(`refs/pull/`)) { + gitRef = github.context.sha; + } + return gitRef; + } + static gitContext() { + return `${github_1.GitHub.serverURL}/${github.context.repo.owner}/${github.context.repo.repo}.git#${Context.gitRef()}`; + } + static provenanceBuilderID() { + return `${github_1.GitHub.serverURL}/${github.context.repo.owner}/${github.context.repo.repo}/actions/runs/${github.context.runId}`; + } +} +exports.Context = Context; +Context._tmpDir = fs_1.default.mkdtempSync(path_1.default.join(Context.ensureDirExists(process.env.RUNNER_TEMP || os_1.default.tmpdir()), 'docker-actions-toolkit-')); +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/lib/context.js.map b/lib/context.js.map new file mode 100644 index 00000000..7052701d --- /dev/null +++ b/lib/context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,4CAAoB;AACpB,4CAAoB;AACpB,gDAAwB;AACxB,yCAA2B;A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I,iBAAiB,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IAC7H,CAAC;;AAjCH,0BAkCC;AAjCyB,eAAO,GAAG,YAAE,CAAC,WAAW,CAAC,cAAI,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,YAAE,CAAC,MAAM,EAAE,CAAC,EAAE,yBAAyB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib/docker/assets.d.ts b/lib/docker/assets.d.ts new file mode 100644 index 00000000..01c3281a --- /dev/null +++ b/lib/docker/assets.d.ts @@ -0,0 +1,21 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const setupDockerWinPs1: () => string; +export declare const dockerServiceLogsPs1: () => string; +export declare const limaYaml: () => string; +export declare const setupDockerWinPs1Data = "\n[CmdletBinding()]\nparam(\n [Parameter(Mandatory = $true)]\n [string]$ToolDir,\n\n [Parameter(Mandatory = $true)]\n [string]$RunDir,\n\n [Parameter(Mandatory = $true)]\n [string]$DockerHost,\n\n [Parameter(Mandatory = $false)]\n [string]$DaemonConfig)\n\n$pwver = (Get-ItemProperty -Path HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion\nWrite-Host \"PowerShell version: $pwver\"\n\n# Create run directory\nNew-Item -ItemType Directory \"$RunDir\" -ErrorAction SilentlyContinue | Out-Null\n\n# Remove existing service\nif (Get-Service docker -ErrorAction SilentlyContinue) {\n $dockerVersion = (docker version -f \"{{.Server.Version}}\")\n Write-Host \"Current installed Docker version: $dockerVersion\"\n # stop service\n Stop-Service -Force -Name docker\n Write-Host \"Service stopped\"\n # remove service\n sc.exe delete \"docker\"\n # removes event log entry. we could use \"Remove-EventLog -LogName -Source docker\"\n # but this cmd is not available atm\n $ErrorActionPreference = \"SilentlyContinue\"\n & reg delete \"HKLM\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\docker\" /f 2>&1 | Out-Null\n $ErrorActionPreference = \"Stop\"\n Write-Host \"Service removed\"\n}\n\n$env:Path = \"$ToolDir;\" + [System.Environment]::GetEnvironmentVariable(\"Path\",\"Machine\") + \";\" + [System.Environment]::GetEnvironmentVariable(\"Path\",\"User\")\nWrite-Host \"Path: $env:Path\"\n\n$env:DOCKER_HOST = $DockerHost\nWrite-Host \"DOCKER_HOST: $env:DOCKER_HOST\"\n\nif ($DaemonConfig) {\n Write-Host \"Writing Docker daemon config\"\n New-Item -ItemType Directory -Force -Path \"$env:ProgramData\\Docker\\config\"\n $DaemonConfig | Out-File -FilePath \"$env:ProgramData\\Docker\\config\\daemon.json\"\n}\n\nWrite-Host \"Creating service\"\nNew-Item -ItemType Directory \"$RunDir\\moby-root\" -ErrorAction SilentlyContinue | Out-Null\nNew-Item -ItemType Directory \"$RunDir\\moby-exec\" -ErrorAction SilentlyContinue | Out-Null\nStart-Process -Wait -NoNewWindow \"$ToolDir\\dockerd\" `\n -ArgumentList `\n \"--host=$DockerHost\", `\n \"--data-root=$RunDir\\moby-root\", `\n \"--exec-root=$RunDir\\moby-exec\", `\n \"--pidfile=$RunDir\\docker.pid\", `\n \"--register-service\"\nWrite-Host \"Starting service\"\nStart-Service -Name docker\nWrite-Host \"Service started successfully!\"\n\n$tries=20\nWrite-Host \"Waiting for Docker daemon to start...\"\nWhile ($true) {\n $ErrorActionPreference = \"SilentlyContinue\"\n & \"$ToolDir\\docker\" version | Out-Null\n $ErrorActionPreference = \"Stop\"\n If ($LastExitCode -eq 0) {\n break\n }\n $tries--\n If ($tries -le 0) {\n Throw \"Failed to get a response from Docker daemon\"\n }\n Write-Host -NoNewline \".\"\n Start-Sleep -Seconds 1\n}\nWrite-Host \"Docker daemon started successfully!\"\n"; +export declare const dockerServiceLogsPs1Data = "\nGet-WinEvent -ea SilentlyContinue `\n -FilterHashtable @{ProviderName= \"docker\"; LogName = \"application\"} |\n Sort-Object @{Expression=\"TimeCreated\";Descending=$false} |\n ForEach-Object {\"$($_.TimeCreated.ToUniversalTime().ToString(\"o\")) [$($_.LevelDisplayName)] $($_.Message)\"}\n"; +export declare const limaYamlData = "\n# VM type: \"qemu\" or \"vz\" (on macOS 13 and later).\n# The vmType can be specified only on creating the instance.\n# The vmType of existing instances cannot be changed.\n# Builtin default: \"qemu\"\nvmType: qemu\n\n# OS: \"Linux\".\n# Builtin default: \"Linux\"\nos: null\n\n# Arch: \"default\", \"x86_64\", \"aarch64\".\n# Builtin default: \"default\" (corresponds to the host architecture)\narch: null\n\nimages:\n{{#each customImages}}\n- location: \"{{location}}\"\n arch: \"{{arch}}\"\n digest: \"{{digest}}\"\n{{/each}}\n- location: \"https://cloud-images.ubuntu.com/releases/22.04/release-20231026/ubuntu-22.04-server-cloudimg-amd64.img\"\n arch: \"x86_64\"\n digest: \"sha256:054db2d88c454bb0ad8dfd8883955e3946b57d2b0bf0d023f3ade3c93cdd14e5\"\n- location: \"https://cloud-images.ubuntu.com/releases/22.04/release-20231026/ubuntu-22.04-server-cloudimg-arm64.img\"\n arch: \"aarch64\"\n digest: \"sha256:eafa7742ce5ff109222ea313d31ea366d587b4e89b900b11d8285ae775dfe8c3\"\n\n# CPUs\n# Builtin default: min(4, host CPU cores)\ncpus: null\n\n# Memory size\n# Builtin default: min(\"4GiB\", half of host memory)\nmemory: null\n\n# Disk size\n# Builtin default: \"100GiB\"\ndisk: 60GiB\n\n# Expose host directories to the guest, the mount point might be accessible from all UIDs in the guest\n# Builtin default: null (Mount nothing)\n# This file: Mount the home as read-only, /tmp/lima as writable\nmounts:\n- location: \"~\"\n- location: \"/tmp/lima\"\n writable: true\n\n# Mount type for above mounts, such as \"reverse-sshfs\" (from sshocker), \"9p\" (EXPERIMENTAL, from QEMU\u2019s virtio-9p-pci, aka virtfs),\n# or \"virtiofs\" (EXPERIMENTAL, needs `vmType: vz`)\n# Builtin default: \"reverse-sshfs\" (for QEMU), \"virtiofs\" (for vz)\nmountType: null\n\ncontainerd:\n system: false\n user: false\n\nprovision:\n- mode: system\n # This script defines the host.docker.internal hostname when hostResolver is disabled.\n # It is also needed for lima 0.8.2 and earlier, which does not support hostResolver.hosts.\n # Names defined in /etc/hosts inside the VM are not resolved inside containers when\n # using the hostResolver; use hostResolver.hosts instead (requires lima 0.8.3 or later).\n script: |\n #!/bin/sh\n sed -i 's/host.lima.internal.*/host.lima.internal host.docker.internal/' /etc/hosts\n- mode: system\n script: |\n #!/bin/sh\n apt-get install -f -y iptables\n- mode: system\n script: |\n #!/bin/bash\n set -eux -o pipefail\n command -v docker >/dev/null 2>&1 && exit 0\n if [ ! -e /etc/systemd/system/docker.socket.d/override.conf ]; then\n mkdir -p /etc/systemd/system/docker.socket.d\n # Alternatively we could just add the user to the \"docker\" group, but that requires restarting the user session\n cat <<-EOF >/etc/systemd/system/docker.socket.d/override.conf\n [Socket]\n SocketUser=${LIMA_CIDATA_USER}\n EOF\n fi\n if [ ! -e /etc/docker/daemon.json ]; then\n mkdir -p /etc/docker\n cat <<-EOF >/etc/docker/daemon.json\n {{stringify daemonConfig}}\n EOF\n fi\n export DEBIAN_FRONTEND=noninteractive\n curl -fsSL https://get.docker.com | sh -s -- --channel {{dockerBinChannel}} --version {{dockerBinVersion}}\n\nprobes:\n- script: |\n #!/bin/bash\n set -eux -o pipefail\n if ! timeout 30s bash -c \"until command -v docker >/dev/null 2>&1; do sleep 3; done\"; then\n echo >&2 \"docker is not installed yet\"\n exit 1\n fi\n if ! timeout 30s bash -c \"until pgrep dockerd; do sleep 3; done\"; then\n echo >&2 \"dockerd is not running\"\n exit 1\n fi\n hint: See \"/var/log/cloud-init-output.log\". in the guest\n\nhostResolver:\n # hostResolver.hosts requires lima 0.8.3 or later. Names defined here will also\n # resolve inside containers, and not just inside the VM itself.\n hosts:\n host.docker.internal: host.lima.internal\n\nportForwards:\n- guestSocket: \"/var/run/docker.sock\"\n hostSocket: \"{{dockerSock}}\"\n\naudio:\n # EXPERIMENTAL\n # QEMU audiodev, e.g., \"none\", \"coreaudio\", \"pa\", \"alsa\", \"oss\".\n # VZ driver, use \"vz\" as device name\n # Choosing \"none\" will mute the audio output, and not play any sound.\n # Builtin default: \"\"\n device: none\n"; diff --git a/lib/docker/assets.js b/lib/docker/assets.js new file mode 100644 index 00000000..2efa1e16 --- /dev/null +++ b/lib/docker/assets.js @@ -0,0 +1,259 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.limaYamlData = exports.dockerServiceLogsPs1Data = exports.setupDockerWinPs1Data = exports.limaYaml = exports.dockerServiceLogsPs1 = exports.setupDockerWinPs1 = void 0; +const fs_1 = __importDefault(require("fs")); +const context_1 = require("../context"); +const setupDockerWinPs1 = () => { + return get('docker-setup-win.ps1', exports.setupDockerWinPs1Data); +}; +exports.setupDockerWinPs1 = setupDockerWinPs1; +const dockerServiceLogsPs1 = () => { + return get('docker-service-logs.ps1', exports.dockerServiceLogsPs1Data); +}; +exports.dockerServiceLogsPs1 = dockerServiceLogsPs1; +const limaYaml = () => { + return get('lima.yaml', exports.limaYamlData); +}; +exports.limaYaml = limaYaml; +const get = (filename, data, mode) => { + const assetPath = context_1.Context.tmpName({ + template: `docker-asset-XXXXXX-${filename}`, + tmpdir: context_1.Context.tmpDir() + }); + fs_1.default.writeFileSync(assetPath, data); + if (mode) { + fs_1.default.chmodSync(assetPath, mode); + } + return assetPath; +}; +exports.setupDockerWinPs1Data = ` +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$ToolDir, + + [Parameter(Mandatory = $true)] + [string]$RunDir, + + [Parameter(Mandatory = $true)] + [string]$DockerHost, + + [Parameter(Mandatory = $false)] + [string]$DaemonConfig) + +$pwver = (Get-ItemProperty -Path HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion +Write-Host "PowerShell version: $pwver" + +# Create run directory +New-Item -ItemType Directory "$RunDir" -ErrorAction SilentlyContinue | Out-Null + +# Remove existing service +if (Get-Service docker -ErrorAction SilentlyContinue) { + $dockerVersion = (docker version -f "{{.Server.Version}}") + Write-Host "Current installed Docker version: $dockerVersion" + # stop service + Stop-Service -Force -Name docker + Write-Host "Service stopped" + # remove service + sc.exe delete "docker" + # removes event log entry. we could use "Remove-EventLog -LogName -Source docker" + # but this cmd is not available atm + $ErrorActionPreference = "SilentlyContinue" + & reg delete "HKLM\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\docker" /f 2>&1 | Out-Null + $ErrorActionPreference = "Stop" + Write-Host "Service removed" +} + +$env:Path = "$ToolDir;" + [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +Write-Host "Path: $env:Path" + +$env:DOCKER_HOST = $DockerHost +Write-Host "DOCKER_HOST: $env:DOCKER_HOST" + +if ($DaemonConfig) { + Write-Host "Writing Docker daemon config" + New-Item -ItemType Directory -Force -Path "$env:ProgramData\\Docker\\config" + $DaemonConfig | Out-File -FilePath "$env:ProgramData\\Docker\\config\\daemon.json" +} + +Write-Host "Creating service" +New-Item -ItemType Directory "$RunDir\\moby-root" -ErrorAction SilentlyContinue | Out-Null +New-Item -ItemType Directory "$RunDir\\moby-exec" -ErrorAction SilentlyContinue | Out-Null +Start-Process -Wait -NoNewWindow "$ToolDir\\dockerd" \` + -ArgumentList \` + "--host=$DockerHost", \` + "--data-root=$RunDir\\moby-root", \` + "--exec-root=$RunDir\\moby-exec", \` + "--pidfile=$RunDir\\docker.pid", \` + "--register-service" +Write-Host "Starting service" +Start-Service -Name docker +Write-Host "Service started successfully!" + +$tries=20 +Write-Host "Waiting for Docker daemon to start..." +While ($true) { + $ErrorActionPreference = "SilentlyContinue" + & "$ToolDir\\docker" version | Out-Null + $ErrorActionPreference = "Stop" + If ($LastExitCode -eq 0) { + break + } + $tries-- + If ($tries -le 0) { + Throw "Failed to get a response from Docker daemon" + } + Write-Host -NoNewline "." + Start-Sleep -Seconds 1 +} +Write-Host "Docker daemon started successfully!" +`; +exports.dockerServiceLogsPs1Data = ` +Get-WinEvent -ea SilentlyContinue \` + -FilterHashtable @{ProviderName= "docker"; LogName = "application"} | + Sort-Object @{Expression="TimeCreated";Descending=$false} | + ForEach-Object {"$($_.TimeCreated.ToUniversalTime().ToString("o")) [$($_.LevelDisplayName)] $($_.Message)"} +`; +exports.limaYamlData = ` +# VM type: "qemu" or "vz" (on macOS 13 and later). +# The vmType can be specified only on creating the instance. +# The vmType of existing instances cannot be changed. +# Builtin default: "qemu" +vmType: qemu + +# OS: "Linux". +# Builtin default: "Linux" +os: null + +# Arch: "default", "x86_64", "aarch64". +# Builtin default: "default" (corresponds to the host architecture) +arch: null + +images: +{{#each customImages}} +- location: "{{location}}" + arch: "{{arch}}" + digest: "{{digest}}" +{{/each}} +- location: "https://cloud-images.ubuntu.com/releases/22.04/release-20231026/ubuntu-22.04-server-cloudimg-amd64.img" + arch: "x86_64" + digest: "sha256:054db2d88c454bb0ad8dfd8883955e3946b57d2b0bf0d023f3ade3c93cdd14e5" +- location: "https://cloud-images.ubuntu.com/releases/22.04/release-20231026/ubuntu-22.04-server-cloudimg-arm64.img" + arch: "aarch64" + digest: "sha256:eafa7742ce5ff109222ea313d31ea366d587b4e89b900b11d8285ae775dfe8c3" + +# CPUs +# Builtin default: min(4, host CPU cores) +cpus: null + +# Memory size +# Builtin default: min("4GiB", half of host memory) +memory: null + +# Disk size +# Builtin default: "100GiB" +disk: 60GiB + +# Expose host directories to the guest, the mount point might be accessible from all UIDs in the guest +# Builtin default: null (Mount nothing) +# This file: Mount the home as read-only, /tmp/lima as writable +mounts: +- location: "~" +- location: "/tmp/lima" + writable: true + +# Mount type for above mounts, such as "reverse-sshfs" (from sshocker), "9p" (EXPERIMENTAL, from QEMU’s virtio-9p-pci, aka virtfs), +# or "virtiofs" (EXPERIMENTAL, needs \`vmType: vz\`) +# Builtin default: "reverse-sshfs" (for QEMU), "virtiofs" (for vz) +mountType: null + +containerd: + system: false + user: false + +provision: +- mode: system + # This script defines the host.docker.internal hostname when hostResolver is disabled. + # It is also needed for lima 0.8.2 and earlier, which does not support hostResolver.hosts. + # Names defined in /etc/hosts inside the VM are not resolved inside containers when + # using the hostResolver; use hostResolver.hosts instead (requires lima 0.8.3 or later). + script: | + #!/bin/sh + sed -i 's/host.lima.internal.*/host.lima.internal host.docker.internal/' /etc/hosts +- mode: system + script: | + #!/bin/sh + apt-get install -f -y iptables +- mode: system + script: | + #!/bin/bash + set -eux -o pipefail + command -v docker >/dev/null 2>&1 && exit 0 + if [ ! -e /etc/systemd/system/docker.socket.d/override.conf ]; then + mkdir -p /etc/systemd/system/docker.socket.d + # Alternatively we could just add the user to the "docker" group, but that requires restarting the user session + cat <<-EOF >/etc/systemd/system/docker.socket.d/override.conf + [Socket] + SocketUser=\${LIMA_CIDATA_USER} + EOF + fi + if [ ! -e /etc/docker/daemon.json ]; then + mkdir -p /etc/docker + cat <<-EOF >/etc/docker/daemon.json + {{stringify daemonConfig}} + EOF + fi + export DEBIAN_FRONTEND=noninteractive + curl -fsSL https://get.docker.com | sh -s -- --channel {{dockerBinChannel}} --version {{dockerBinVersion}} + +probes: +- script: | + #!/bin/bash + set -eux -o pipefail + if ! timeout 30s bash -c "until command -v docker >/dev/null 2>&1; do sleep 3; done"; then + echo >&2 "docker is not installed yet" + exit 1 + fi + if ! timeout 30s bash -c "until pgrep dockerd; do sleep 3; done"; then + echo >&2 "dockerd is not running" + exit 1 + fi + hint: See "/var/log/cloud-init-output.log". in the guest + +hostResolver: + # hostResolver.hosts requires lima 0.8.3 or later. Names defined here will also + # resolve inside containers, and not just inside the VM itself. + hosts: + host.docker.internal: host.lima.internal + +portForwards: +- guestSocket: "/var/run/docker.sock" + hostSocket: "{{dockerSock}}" + +audio: + # EXPERIMENTAL + # QEMU audiodev, e.g., "none", "coreaudio", "pa", "alsa", "oss". + # VZ driver, use "vz" as device name + # Choosing "none" will mute the audio output, and not play any sound. + # Builtin default: "" + device: none +`; +//# sourceMappingURL=assets.js.map \ No newline at end of file diff --git a/lib/docker/assets.js.map b/lib/docker/assets.js.map new file mode 100644 index 00000000..50abdf8e --- /dev/null +++ b/lib/docker/assets.js.map @@ -0,0 +1 @@ +{"version":3,"file":"assets.js","sourceRoot":"","sources":["../../src/docker/assets.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;AAEH,4CAAoB;AACpB,wCAAmC;AAE5B,MAAM,iBAAiB,GAAG,GAAW,EAAE;IAC5C,OAAO,GAAG,CAAC,sBAAsB,EAAE,6BAAqB,CAAC,CAAC;AAC5D,CAAC,CAAC;AAFW,QAAA,iBAAiB,qBAE5B;AAEK,MAAM,oBAAoB,GAAG,GAAW,EAAE;IAC/C,OAAO,GAAG,CAAC,yBAAyB,EAAE,gCAAwB,CAAC,CAAC;AAClE,CAAC,CAAC;AAFW,QAAA,oBAAoB,wBAE/B;AAEK,MAAM,QAAQ,GAAG,GAAW,EAAE;IACnC,OAAO,GAAG,CAAC,WAAW,EAAE,oBAAY,CAAC,CAAC;AACxC,CAAC,CAAC;AAFW,QAAA,QAAQ,YAEnB;AAEF,MAAM,GAAG,GAAG,CAAC,QAAgB,EAAE,IAAY,EAAE,IAAa,EAAU,EAAE;IACpE,MAAM,SAAS,GAAG,iBAAO,CAAC,OAAO,CAAC;QAChC,QAAQ,EAAE,uBAAuB,QAAQ,EAAE;QAC3C,MAAM,EAAE,iBAAO,CAAC,MAAM,EAAE;KACzB,CAAC,CAAC;IACH,YAAE,CAAC,aAAa,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAClC,IAAI,IAAI,EAAE,CAAC;QACT,YAAE,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAEW,QAAA,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiFpC,CAAC;AAEW,QAAA,wBAAwB,GAAG;;;;;CAKvC,CAAC;AAEW,QAAA,YAAY,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2H3B,CAAC"} \ No newline at end of file diff --git a/lib/docker/docker.d.ts b/lib/docker/docker.d.ts new file mode 100644 index 00000000..60c36247 --- /dev/null +++ b/lib/docker/docker.d.ts @@ -0,0 +1,29 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ConfigFile } from '../types/docker/docker'; +export declare class Docker { + static get configDir(): string; + static configFile(): ConfigFile | undefined; + static isAvailable(): Promise; + static context(name?: string): Promise; + static printVersion(): Promise; + static printInfo(): Promise; + static parseRepoTag(image: string): { + repository: string; + tag: string; + }; + static pull(image: string, cache?: boolean): Promise; +} diff --git a/lib/docker/docker.js b/lib/docker/docker.js new file mode 100644 index 00000000..9d94dc83 --- /dev/null +++ b/lib/docker/docker.js @@ -0,0 +1,205 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Docker = void 0; +const fs_1 = __importDefault(require("fs")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +const core = __importStar(require("@actions/core")); +const io = __importStar(require("@actions/io")); +const context_1 = require("../context"); +const cache_1 = require("../cache"); +const exec_1 = require("../exec"); +const util_1 = require("../util"); +class Docker { + static get configDir() { + return process.env.DOCKER_CONFIG || path_1.default.join(os_1.default.homedir(), '.docker'); + } + static configFile() { + const f = path_1.default.join(Docker.configDir, 'config.json'); + if (!fs_1.default.existsSync(f)) { + return undefined; + } + return JSON.parse(fs_1.default.readFileSync(f, { encoding: 'utf-8' })); + } + static isAvailable() { + return __awaiter(this, void 0, void 0, function* () { + return yield io + .which('docker', true) + .then(res => { + core.debug(`Docker.isAvailable ok: ${res}`); + return true; + }) + .catch(error => { + core.debug(`Docker.isAvailable error: ${error}`); + return false; + }); + }); + } + static context(name) { + return __awaiter(this, void 0, void 0, function* () { + const args = ['context', 'inspect', '--format', '{{.Name}}']; + if (name) { + args.push(name); + } + return yield exec_1.Exec.getExecOutput(`docker`, args, { + ignoreReturnCode: true, + silent: true + }).then(res => { + if (res.stderr.length > 0 && res.exitCode != 0) { + throw new Error(res.stderr); + } + return res.stdout.trim(); + }); + }); + } + static printVersion() { + return __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('docker', ['version']); + }); + } + static printInfo() { + return __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('docker', ['info']); + }); + } + static parseRepoTag(image) { + let sepPos; + const digestPos = image.indexOf('@'); + const colonPos = image.lastIndexOf(':'); + if (digestPos >= 0) { + // priority on digest + sepPos = digestPos; + } + else if (colonPos >= 0) { + sepPos = colonPos; + } + else { + return { + repository: image, + tag: 'latest' + }; + } + const tag = image.slice(sepPos + 1); + if (tag.indexOf('/') === -1) { + return { + repository: image.slice(0, sepPos), + tag: tag + }; + } + return { + repository: image, + tag: 'latest' + }; + } + static pull(image, cache) { + return __awaiter(this, void 0, void 0, function* () { + const parsedImage = Docker.parseRepoTag(image); + const repoSanitized = parsedImage.repository.replace(/[^a-zA-Z0-9.]+/g, '--'); + const tagSanitized = parsedImage.tag.replace(/[^a-zA-Z0-9.]+/g, '--'); + const imageCache = new cache_1.Cache({ + htcName: repoSanitized, + htcVersion: tagSanitized, + baseCacheDir: path_1.default.join(Docker.configDir, '.cache', 'images', repoSanitized), + cacheFile: 'image.tar' + }); + let cacheFoundPath; + if (cache) { + cacheFoundPath = yield imageCache.find(); + if (cacheFoundPath) { + core.info(`Image found from cache in ${cacheFoundPath}`); + yield exec_1.Exec.getExecOutput(`docker`, ['load', '-i', cacheFoundPath], { + ignoreReturnCode: true + }).then(res => { + var _a, _b, _c; + if (res.stderr.length > 0 && res.exitCode != 0) { + core.warning(`Failed to load image from cache: ${(_c = (_b = (_a = res.stderr.match(/(.*)\s*$/)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : 'unknown error'}`); + } + }); + } + } + let pulled = true; + yield exec_1.Exec.getExecOutput(`docker`, ['pull', image], { + ignoreReturnCode: true + }).then(res => { + var _a, _b, _c; + if (res.stderr.length > 0 && res.exitCode != 0) { + pulled = false; + const err = (_c = (_b = (_a = res.stderr.match(/(.*)\s*$/)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : 'unknown error'; + if (cacheFoundPath) { + core.warning(`Failed to pull image, using one from cache: ${err}`); + } + else { + throw new Error(err); + } + } + }); + if (cache && pulled) { + const imageTarPath = path_1.default.join(context_1.Context.tmpDir(), `${util_1.Util.hash(image)}.tar`); + yield exec_1.Exec.getExecOutput(`docker`, ['save', '-o', imageTarPath, image], { + ignoreReturnCode: true + }).then((res) => __awaiter(this, void 0, void 0, function* () { + var _a, _b, _c; + if (res.stderr.length > 0 && res.exitCode != 0) { + core.warning(`Failed to save image: ${(_c = (_b = (_a = res.stderr.match(/(.*)\s*$/)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : 'unknown error'}`); + } + else { + const cachePath = yield imageCache.save(imageTarPath); + core.info(`Image cached to ${cachePath}`); + } + })); + } + }); + } +} +exports.Docker = Docker; +//# sourceMappingURL=docker.js.map \ No newline at end of file diff --git a/lib/docker/docker.js.map b/lib/docker/docker.js.map new file mode 100644 index 00000000..9586e692 --- /dev/null +++ b/lib/docker/docker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"docker.js","sourceRoot":"","sources":["../../src/docker/docker.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,4CAAoB;AACpB,4CAAoB;AACpB,gDAAwB;AACxB,oDAAsC;AACtC,gDAAkC;AAElC,wCAAmC;AACnC,oCAA+B;AAC/B,kCAA6B;AAC7B,kCAA6B;AAI7B,MAAa,MAAM;IACjB,MAAM,KAAK,SAAS;QAClB,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,cAAI,CAAC,IAAI,CAAC,YAAE,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAC;IACzE,CAAC;IAEM,MAAM,CAAC,UAAU;QACtB,MAAM,CAAC,GAAG,cAAI,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;QACrD,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;YACtB,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAmB,IAAI,CAAC,KAAK,CAAC,YAAE,CAAC,YA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AC,IAAI,CAAC,YAAY,CAAC,CAAC;wBACtD,IAAI,CAAC,IAAI,CAAC,mBAAmB,SAAS,EAAE,CAAC,CAAC;oBAC5C,CAAC;gBACH,CAAC,CAAA,CAAC,CAAC;YACL,CAAC;QACH,CAAC;KAAA;CACF;AAtID,wBAsIC"} \ No newline at end of file diff --git a/lib/docker/install.d.ts b/lib/docker/install.d.ts new file mode 100644 index 00000000..6f3db248 --- /dev/null +++ b/lib/docker/install.d.ts @@ -0,0 +1,57 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GitHubRelease } from '../types/github'; +export interface InstallOpts { + version?: string; + channel?: string; + runDir: string; + contextName?: string; + daemonConfig?: string; +} +interface LimaImage { + location: string; + arch: string; + digest?: string; +} +export declare class Install { + private readonly runDir; + private readonly version; + private readonly channel; + private readonly contextName; + private readonly daemonConfig?; + private _version; + private _toolDir; + private readonly limaInstanceName; + constructor(opts: InstallOpts); + get toolDir(): string; + download(): Promise; + install(): Promise; + private installDarwin; + private installLinux; + private installWindows; + tearDown(): Promise; + private tearDownDarwin; + private tearDownLinux; + private tearDownWindows; + private downloadURL; + private static platformOS; + private static platformArch; + private static limaInstalled; + private static qemuArch; + static getRelease(version: string): Promise; + static limaCustomImages(): LimaImage[]; +} +export {}; diff --git a/lib/docker/install.js b/lib/docker/install.js new file mode 100644 index 00000000..8af22f9c --- /dev/null +++ b/lib/docker/install.js @@ -0,0 +1,535 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Install = void 0; +const child_process = __importStar(require("child_process")); +const fs_1 = __importDefault(require("fs")); +const promises_1 = __importDefault(require("fs/promises")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +const async_retry_1 = __importDefault(require("async-retry")); +const handlebars = __importStar(require("handlebars")); +const util = __importStar(require("util")); +const core = __importStar(require("@actions/core")); +const httpm = __importStar(require("@actions/http-client")); +const io = __importStar(require("@actions/io")); +const tc = __importStar(require("@actions/tool-cache")); +const context_1 = require("../context"); +const exec_1 = require("../exec"); +const util_1 = require("../util"); +const assets_1 = require("./assets"); +class Install { + constructor(opts) { + this.limaInstanceName = 'docker-actions-toolkit'; + this.runDir = opts.runDir; + this.version = opts.version || 'latest'; + this.channel = opts.channel || 'stable'; + this.contextName = opts.contextName || 'setup-docker-action'; + this.daemonConfig = opts.daemonConfig; + } + get toolDir() { + return this._toolDir || context_1.Context.tmpDir(); + } + download() { + return __awaiter(this, void 0, void 0, function* () { + const release = yield Install.getRelease(this.version); + this._version = release.tag_name.replace(/^v+|v+$/g, ''); + core.debug(`docker.Install.download version: ${this._version}`); + const downloadURL = this.downloadURL(this._version, this.channel); + core.info(`Downloading ${downloadURL}`); + const downloadPath = yield tc.downloadTool(downloadURL); + core.debug(`docker.Install.download downloadPath: ${downloadPath}`); + let extractFolder; + if (os_1.default.platform() == 'win32') { + extractFolder = yield tc.extractZip(downloadPath); + } + else { + extractFolder = yield tc.extractTar(downloadPath); + } + if (util_1.Util.isDirectory(path_1.default.join(extractFolder, 'docker'))) { + extractFolder = path_1.default.join(extractFolder, 'docker'); + } + core.debug(`docker.Install.download extractFolder: ${extractFolder}`); + core.info('Fixing perms'); + fs_1.default.readdir(path_1.default.join(extractFolder), function (err, files) { + if (err) { + throw err; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + files.forEach(function (file, index) { + fs_1.default.chmodSync(path_1.default.join(extractFolder, file), '0755'); + }); + }); + const tooldir = yield tc.cacheDir(extractFolder, `docker-${this.channel}`, this._version.replace(/(0+)([1-9]+)/, '$2')); + core.addPath(tooldir); + core.info('Added Docker to PATH'); + this._toolDir = tooldir; + return tooldir; + }); + } + install() { + return __awaiter(this, void 0, void 0, function* () { + if (!this.toolDir) { + throw new Error('toolDir must be set. Run download first.'); + } + if (!this.runDir) { + throw new Error('runDir must be set'); + } + switch (os_1.default.platform()) { + case 'darwin': { + return yield this.installDarwin(); + } + case 'linux': { + return yield this.installLinux(); + } + case 'win32': { + return yield this.installWindows(); + } + default: { + throw new Error(`Unsupported platform: ${os_1.default.platform()}`); + } + } + }); + } + installDarwin() { + return __awaiter(this, void 0, void 0, function* () { + const limaDir = path_1.default.join(os_1.default.homedir(), '.lima', this.limaInstanceName); + yield io.mkdirP(limaDir); + const dockerHost = `unix://${limaDir}/docker.sock`; + // avoid brew to auto update and upgrade unrelated packages. + let envs = Object.assign({}, process.env, { + HOMEBREW_NO_AUTO_UPDATE: '1', + HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: '1' + }); + if (!(yield Install.limaInstalled())) { + yield core.group('Installing lima', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('brew', ['install', 'lima'], { env: envs }); + })); + } + yield core.group('Lima version', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('lima', ['--version'], { env: envs }); + })); + yield core.group('Creating lima config', () => __awaiter(this, void 0, void 0, function* () { + let limaDaemonConfig = {}; + if (this.daemonConfig) { + limaDaemonConfig = JSON.parse(this.daemonConfig); + } + handlebars.registerHelper('stringify', function (obj) { + return new handlebars.SafeString(JSON.stringify(obj)); + }); + const limaCfg = handlebars.compile(assets_1.limaYamlData)({ + customImages: Install.limaCustomImages(), + daemonConfig: limaDaemonConfig, + dockerSock: `${limaDir}/docker.sock`, + dockerBinVersion: this._version, + dockerBinChannel: this.channel + }); + core.info(`Writing lima config to ${path_1.default.join(limaDir, 'lima.yaml')}`); + fs_1.default.writeFileSync(path_1.default.join(limaDir, 'lima.yaml'), limaCfg); + core.info(limaCfg); + })); + const qemuArch = yield Install.qemuArch(); + yield core.group('QEMU version', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec(`qemu-system-${qemuArch} --version`); + })); + // lima might already be started on the runner so env var added in download + // method is not expanded to the running process. + envs = Object.assign({}, envs, { + PATH: `${this.toolDir}:${process.env.PATH}` + }); + yield core.group('Starting lima instance', () => __awaiter(this, void 0, void 0, function* () { + const limaStartArgs = ['start', `--name=${this.limaInstanceName}`]; + if (process.env.LIMA_START_ARGS) { + limaStartArgs.push(process.env.LIMA_START_ARGS); + } + try { + yield exec_1.Exec.exec(`limactl ${limaStartArgs.join(' ')}`, [], { env: envs }); + } + catch (e) { + promises_1.default + .readdir(limaDir) + .then(files => { + files + .filter(f => path_1.default.extname(f) === '.log') + .forEach(f => { + const logfile = path_1.default.join(limaDir, f); + const logcontent = fs_1.default.readFileSync(logfile, { encoding: 'utf8' }).trim(); + if (logcontent.length > 0) { + core.info(`### ${logfile}:\n${logcontent}`); + } + }); + }) + .catch(() => { + // ignore + }); + throw e; + } + })); + yield core.group('Create Docker context', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('docker', ['context', 'create', this.contextName, '--docker', `host=${dockerHost}`]); + yield exec_1.Exec.exec('docker', ['context', 'use', this.contextName]); + })); + return dockerHost; + }); + } + installLinux() { + return __awaiter(this, void 0, void 0, function* () { + const dockerHost = `unix://${path_1.default.join(this.runDir, 'docker.sock')}`; + yield io.mkdirP(this.runDir); + const daemonConfigPath = path_1.default.join(this.runDir, 'daemon.json'); + yield fs_1.default.writeFileSync(daemonConfigPath, '{}'); + let daemonConfig = undefined; + const daemonConfigDefaultPath = '/etc/docker/daemon.json'; + if (fs_1.default.existsSync(daemonConfigDefaultPath)) { + yield core.group('Default Docker daemon config found', () => __awaiter(this, void 0, void 0, function* () { + core.info(JSON.stringify(JSON.parse(fs_1.default.readFileSync(daemonConfigDefaultPath, { encoding: 'utf8' })), null, 2)); + })); + daemonConfig = JSON.parse(fs_1.default.readFileSync(daemonConfigDefaultPath, { encoding: 'utf8' })); + } + if (this.daemonConfig) { + daemonConfig = Object.assign(daemonConfig || {}, JSON.parse(this.daemonConfig)); + } + if (daemonConfig) { + const daemonConfigStr = JSON.stringify(daemonConfig, null, 2); + yield core.group('Writing Docker daemon config', () => __awaiter(this, void 0, void 0, function* () { + fs_1.default.writeFileSync(daemonConfigPath, daemonConfigStr); + core.info(daemonConfigStr); + })); + } + const envs = Object.assign({}, process.env, { + PATH: `${this.toolDir}:${process.env.PATH}` + }); + yield core.group('Start Docker daemon', () => __awaiter(this, void 0, void 0, function* () { + const bashPath = yield io.which('bash', true); + const cmd = `${this.toolDir}/dockerd --host="${dockerHost}" --config-file="${daemonConfigPath}" --exec-root="${this.runDir}/execroot" --data-root="${this.runDir}/data" --pidfile="${this.runDir}/docker.pid" --userland-proxy=false`; + core.info(`[command] ${cmd}`); // https://github.com/actions/toolkit/blob/3d652d3133965f63309e4b2e1c8852cdbdcb3833/packages/exec/src/toolrunner.ts#L47 + const proc = yield child_process.spawn( + // We can't use Exec.exec here because we need to detach the process to + // avoid killing it when the action finishes running. Even if detached, + // we also need to run dockerd in a subshell and unref the process so + // GitHub Action doesn't wait for it to finish. + `sudo env "PATH=$PATH" ${bashPath} << EOF +( ${cmd} 2>&1 | tee "${this.runDir}/dockerd.log" ) & +EOF`, [], { + env: envs, + detached: true, + shell: true, + stdio: ['ignore', process.stdout, process.stderr] + }); + proc.unref(); + yield util_1.Util.sleep(3); + const retries = 10; + yield (0, async_retry_1.default)((bail) => __awaiter(this, void 0, void 0, function* () { + try { + yield exec_1.Exec.getExecOutput(`docker version`, undefined, { + silent: true, + env: Object.assign({}, envs, { + DOCKER_HOST: dockerHost + }) + }); + } + catch (e) { + bail(e); + } + }), { + retries: retries, + minTimeout: 1000, + onRetry: (err, i) => { + core.info(`${err}. Retrying (${i}/${retries})...`); + } + }); + core.info(`Docker daemon started started successfully`); + })); + yield core.group('Create Docker context', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('docker', ['context', 'create', this.contextName, '--docker', `host=${dockerHost}`]); + yield exec_1.Exec.exec('docker', ['context', 'use', this.contextName]); + })); + return dockerHost; + }); + } + installWindows() { + return __awaiter(this, void 0, void 0, function* () { + const dockerHost = 'npipe:////./pipe/setup_docker_action'; + let daemonConfig = undefined; + const daemonConfigPath = path_1.default.join(this.runDir, 'daemon.json'); + if (fs_1.default.existsSync(daemonConfigPath)) { + yield core.group('Default Docker daemon config found', () => __awaiter(this, void 0, void 0, function* () { + core.info(JSON.stringify(JSON.parse(fs_1.default.readFileSync(daemonConfigPath, { encoding: 'utf8' })), null, 2)); + })); + daemonConfig = JSON.parse(fs_1.default.readFileSync(daemonConfigPath, { encoding: 'utf8' })); + } + if (this.daemonConfig) { + daemonConfig = Object.assign(daemonConfig || {}, JSON.parse(this.daemonConfig)); + } + let daemonConfigStr = '{}'; + if (daemonConfig) { + daemonConfigStr = JSON.stringify(daemonConfig, null, 2); + yield core.group('Docker daemon config', () => __awaiter(this, void 0, void 0, function* () { + core.info(daemonConfigStr); + })); + } + yield core.group('Install Docker daemon service', () => __awaiter(this, void 0, void 0, function* () { + const setupCmd = yield util_1.Util.powershellCommand((0, assets_1.setupDockerWinPs1)(), { + ToolDir: this.toolDir, + RunDir: this.runDir, + DockerHost: dockerHost, + DaemonConfig: daemonConfigStr + }); + yield exec_1.Exec.exec(setupCmd.command, setupCmd.args); + const logCmd = yield util_1.Util.powershellCommand((0, assets_1.dockerServiceLogsPs1)()); + yield exec_1.Exec.exec(logCmd.command, logCmd.args); + })); + yield core.group('Create Docker context', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('docker', ['context', 'create', this.contextName, '--docker', `host=${dockerHost}`]); + yield exec_1.Exec.exec('docker', ['context', 'use', this.contextName]); + })); + return dockerHost; + }); + } + tearDown() { + return __awaiter(this, void 0, void 0, function* () { + if (!this.runDir) { + throw new Error('runDir must be set'); + } + switch (os_1.default.platform()) { + case 'darwin': { + yield this.tearDownDarwin(); + break; + } + case 'linux': { + yield this.tearDownLinux(); + break; + } + case 'win32': { + yield this.tearDownWindows(); + break; + } + default: { + throw new Error(`Unsupported platform: ${os_1.default.platform()}`); + } + } + }); + } + tearDownDarwin() { + return __awaiter(this, void 0, void 0, function* () { + yield core.group('Docker daemon logs', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('limactl', ['shell', '--tty=false', this.limaInstanceName, 'sudo', 'journalctl', '-u', 'docker.service', '-l', '--no-pager']).catch(() => { + core.warning(`Failed to get Docker daemon logs`); + }); + })); + yield core.group('Stopping lima instance', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('limactl', ['stop', '--tty=false', this.limaInstanceName, '--force']); + })); + yield core.group('Removing lima instance', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('limactl', ['delete', '--tty=false', this.limaInstanceName, '--force']); + })); + yield core.group('Removing Docker context', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('docker', ['context', 'rm', '-f', this.contextName]); + })); + yield core.group(`Cleaning up runDir`, () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('sudo', ['rm', '-rf', this.runDir]); + })); + }); + } + tearDownLinux() { + return __awaiter(this, void 0, void 0, function* () { + yield core.group('Docker daemon logs', () => __awaiter(this, void 0, void 0, function* () { + core.info(fs_1.default.readFileSync(path_1.default.join(this.runDir, 'dockerd.log'), { encoding: 'utf8' })); + })); + yield core.group('Stopping Docker daemon', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('sudo', ['kill', '-s', 'SIGTERM', fs_1.default.readFileSync(path_1.default.join(this.runDir, 'docker.pid')).toString().trim()]); + yield util_1.Util.sleep(5); + })); + yield core.group('Removing Docker context', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('docker', ['context', 'rm', '-f', this.contextName]); + })); + yield core.group(`Cleaning up runDir`, () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('sudo', ['rm', '-rf', this.runDir], { + ignoreReturnCode: true, + failOnStdErr: false + }); + })); + }); + } + tearDownWindows() { + return __awaiter(this, void 0, void 0, function* () { + yield core.group('Docker daemon logs', () => __awaiter(this, void 0, void 0, function* () { + const logCmd = yield util_1.Util.powershellCommand((0, assets_1.dockerServiceLogsPs1)()); + yield exec_1.Exec.exec(logCmd.command, logCmd.args); + })); + yield core.group('Removing Docker context', () => __awaiter(this, void 0, void 0, function* () { + yield exec_1.Exec.exec('docker', ['context', 'rm', '-f', this.contextName]); + })); + }); + } + downloadURL(version, channel) { + const platformOS = Install.platformOS(); + const platformArch = Install.platformArch(); + const ext = platformOS === 'win' ? '.zip' : '.tgz'; + return util.format('https://download.docker.com/%s/static/%s/%s/docker-%s%s', platformOS, channel, platformArch, version, ext); + } + static platformOS() { + switch (os_1.default.platform()) { + case 'darwin': { + return 'mac'; + } + case 'linux': { + return 'linux'; + } + case 'win32': { + return 'win'; + } + default: { + return os_1.default.platform(); + } + } + } + static platformArch() { + switch (os_1.default.arch()) { + case 'x64': { + return 'x86_64'; + } + case 'ppc64': { + return 'ppc64le'; + } + case 'arm64': { + return 'aarch64'; + } + case 'arm': { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const arm_version = process.config.variables.arm_version; + switch (arm_version) { + case 6: { + return 'armel'; + } + case 7: { + return 'armhf'; + } + default: { + return `v${arm_version}`; + } + } + } + default: { + return os_1.default.arch(); + } + } + } + static limaInstalled() { + return __awaiter(this, void 0, void 0, function* () { + return yield io + .which('lima', true) + .then(res => { + core.debug(`docker.Install.limaAvailable ok: ${res}`); + return true; + }) + .catch(error => { + core.debug(`docker.Install.limaAvailable error: ${error}`); + return false; + }); + }); + } + static qemuArch() { + return __awaiter(this, void 0, void 0, function* () { + switch (os_1.default.arch()) { + case 'x64': { + return 'x86_64'; + } + case 'arm64': { + return 'aarch64'; + } + default: { + return os_1.default.arch(); + } + } + }); + } + static getRelease(version) { + return __awaiter(this, void 0, void 0, function* () { + const url = `https://raw.githubusercontent.com/docker/actions-toolkit/main/.github/docker-releases.json`; + const http = new httpm.HttpClient('docker-actions-toolkit'); + const resp = yield http.get(url); + const body = yield resp.readBody(); + const statusCode = resp.message.statusCode || 500; + if (statusCode >= 400) { + throw new Error(`Failed to get Docker release ${version} from ${url} with status code ${statusCode}: ${body}`); + } + const releases = JSON.parse(body); + if (!releases[version]) { + throw new Error(`Cannot find Docker release ${version} in ${url}`); + } + return releases[version]; + }); + } + static limaCustomImages() { + const res = []; + const env = process.env.LIMA_IMAGES; + if (!env) { + return res; + } + for (const input of util_1.Util.getList(env, { ignoreComma: true, comment: '#' })) { + const archIndex = input.indexOf(':'); + const arch = input.substring(0, archIndex).trim(); + const digestIndex = input.indexOf('@'); + const location = input.substring(archIndex + 1, digestIndex !== -1 ? digestIndex : undefined).trim(); + const digest = digestIndex !== -1 ? input.substring(digestIndex + 1).trim() : ''; + res.push({ + location: location, + arch: arch, + digest: digest + }); + } + return res; + } +} +exports.Install = Install; +//# sourceMappingURL=install.js.map \ No newline at end of file diff --git a/lib/docker/install.js.map b/lib/docker/install.js.map new file mode 100644 index 00000000..48e8243e --- /dev/null +++ b/lib/docker/install.js.map @@ -0,0 +1 @@ +{"version":3,"file":"install.js","sourceRoot":"","sources":["../../src/docker/install.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,6DAA+C;AAC/C,4CAAoB;AACpB,2DAA8B;AAC9B,4CAAoB;AACpB,gDAAwB;AACxB,8DAAgC;AAChC,uDAAyC;AACzC,2CAA6B;AAC7B,oDAAsC;AACtC,4DAA8C;AAC9C,gDAAkC;AAClC,wDAA0C;AAE1C,wCAAmC;AACnC,kCAA6B;AAC7B,kCAA6B;AAC7B,qCAA+E;AAiB/E,MAAa,OAAO;IAWlB,YAAY,IAAiB;QAFZ,qBAAgB,GAAG,wBAAwB,CAAC;QAG3D,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,QAAQ,CAAC;QACxC,IAAI,CAAC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AAE,EAAC,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAC,CAAC,EAAE,CAAC;YACzE,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACrC,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC;YAClD,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACvC,MAAM,QAAQ,GAAG,KAAK,CAAC,SAAS,CAAC,SAAS,GAAG,CAAC,EAAE,WAAW,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC;YACrG,MAAM,MAAM,GAAG,WAAW,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACjF,GAAG,CAAC,IAAI,CAAC;gBACP,QAAQ,EAAE,QAAQ;gBAClB,IAAI,EAAE,IAAI;gBACV,MAAM,EAAE,MAAM;aACf,CAAC,CAAC;QACL,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AAvfD,0BAufC"} \ No newline at end of file diff --git a/lib/dockerhub.d.ts b/lib/dockerhub.d.ts new file mode 100644 index 00000000..e47d1d11 --- /dev/null +++ b/lib/dockerhub.d.ts @@ -0,0 +1,31 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RepositoryRequest, RepositoryResponse, RepositoryTagsRequest, RepositoryTagsResponse, TokenRequest, UpdateRepoDescriptionRequest } from './types/dockerhub'; +export interface DockerHubOpts { + credentials: TokenRequest; +} +export declare class DockerHub { + private readonly opts; + private readonly httpc; + private constructor(); + static build(opts: DockerHubOpts): Promise; + getRepositoryTags(req: RepositoryTagsRequest): Promise; + getRepositoryAllTags(req: RepositoryTagsRequest): Promise; + getRepository(req: RepositoryRequest): Promise; + updateRepoDescription(req: UpdateRepoDescriptionRequest): Promise; + private static login; + private static handleResponse; +} diff --git a/lib/dockerhub.js b/lib/dockerhub.js new file mode 100644 index 00000000..67366926 --- /dev/null +++ b/lib/dockerhub.js @@ -0,0 +1,156 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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.DockerHub = void 0; +const core = __importStar(require("@actions/core")); +const httpm = __importStar(require("@actions/http-client")); +const http_client_1 = require("@actions/http-client"); +const apiBaseURL = 'https://hub.docker.com'; +const loginURL = `${apiBaseURL}/v2/users/login?refresh_token=true`; +const repositoriesURL = `${apiBaseURL}/v2/repositories/`; +class DockerHub { + constructor(opts, httpc) { + this.opts = opts; + this.httpc = httpc; + } + static build(opts) { + return __awaiter(this, void 0, void 0, function* () { + return new DockerHub(opts, new httpm.HttpClient('docker-actions-toolkit', [], { + headers: { + Authorization: `JWT ${yield DockerHub.login(opts.credentials)}`, + 'Content-Type': 'application/json' + } + })); + }); + } + getRepositoryTags(req) { + return __awaiter(this, void 0, void 0, function* () { + const url = new URL(`${repositoriesURL}${req.namespace}/${req.name}/tags`); + if (req.page) { + url.searchParams.append('page', req.page.toString()); + } + if (req.page_size) { + url.searchParams.append('page_size', req.page_size.toString()); + } + const resp = yield this.httpc.get(url.toString()); + return JSON.parse(yield DockerHub.handleResponse(resp)); + }); + } + getRepositoryAllTags(req) { + return __awaiter(this, void 0, void 0, function* () { + const tags = yield this.getRepositoryTags(req); + while (tags.next) { + const nextURL = new URL(tags.next); + const pageNumber = Number(nextURL.searchParams.get('page')); + const pageSize = Number(nextURL.searchParams.get('page_size')) || undefined; + const nextTags = yield this.getRepositoryTags({ + namespace: req.namespace, + name: req.name, + page: pageNumber, + page_size: pageSize || req.page_size + }); + tags.results.push(...nextTags.results); + tags.next = nextTags.next; + } + return tags; + }); + } + getRepository(req) { + return __awaiter(this, void 0, void 0, function* () { + const resp = yield this.httpc.get(`${repositoriesURL}${req.namespace}/${req.name}`); + return JSON.parse(yield DockerHub.handleResponse(resp)); + }); + } + updateRepoDescription(req) { + return __awaiter(this, void 0, void 0, function* () { + const body = { + full_description: req.full_description + }; + if (req.description) { + body['description'] = req.description; + } + const resp = yield this.httpc.patch(`${repositoriesURL}${req.namespace}/${req.name}`, JSON.stringify(body)); + return JSON.parse(yield DockerHub.handleResponse(resp)); + }); + } + static login(req) { + return __awaiter(this, void 0, void 0, function* () { + const http = new httpm.HttpClient('docker-actions-toolkit', [], { + headers: { + 'Content-Type': 'application/json' + } + }); + const resp = yield http.post(loginURL, JSON.stringify(req)); + const tokenResp = JSON.parse(yield DockerHub.handleResponse(resp)); + core.setSecret(`${tokenResp.token}`); + return `${tokenResp.token}`; + }); + } + static handleResponse(resp) { + return __awaiter(this, void 0, void 0, function* () { + const body = yield resp.readBody(); + resp.message.statusCode = resp.message.statusCode || http_client_1.HttpCodes.InternalServerError; + if (resp.message.statusCode < 200 || resp.message.statusCode >= 300) { + if (resp.message.statusCode == http_client_1.HttpCodes.Unauthorized) { + throw new Error(`Docker Hub API: operation not permitted`); + } + const errResp = JSON.parse(body); + for (const k of ['message', 'detail', 'error']) { + if (errResp[k]) { + throw new Error(`Docker Hub API: bad status code ${resp.message.statusCode}: ${errResp[k]}`); + } + } + throw new Error(`Docker Hub API: bad status code ${resp.message.statusCode}`); + } + return body; + }); + } +} +exports.DockerHub = DockerHub; +//# sourceMappingURL=dockerhub.js.map \ No newline at end of file diff --git a/lib/dockerhub.js.map b/lib/dockerhub.js.map new file mode 100644 index 00000000..e0cacbc1 --- /dev/null +++ b/lib/dockerhub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dockerhub.js","sourceRoot":"","sources":["../src/dockerhub.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;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OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,IAAI,uBAAS,CAAC,mBAAmB,CAAC;YACnF,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,GAAG,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,IAAI,GAAG,EAAE,CAAC;gBACpE,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,IAAI,uBAAS,CAAC,YAAY,EAAE,CAAC;oBACtD,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;gBAC7D,CAAC;gBACD,MAAM,OAAO,GAA2B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;gBACzD,KAAK,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC;oBAC/C,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;wBACf,MAAM,IAAI,KAAK,CAAC,mCAAmC,IAAI,CAAC,OAAO,CAAC,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;oBAC/F,CAAC;gBACH,CAAC;gBACD,MAAM,IAAI,KAAK,CAAC,mCAAmC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;YAChF,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;KAAA;CACF;AAhGD,8BAgGC"} \ No newline at end of file diff --git a/lib/exec.d.ts b/lib/exec.d.ts new file mode 100644 index 00000000..614caee8 --- /dev/null +++ b/lib/exec.d.ts @@ -0,0 +1,20 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ExecOptions, ExecOutput } from '@actions/exec'; +export declare class Exec { + static exec(commandLine: string, args?: string[], options?: ExecOptions): Promise; + static getExecOutput(commandLine: string, args?: string[], options?: ExecOptions): Promise; +} diff --git a/lib/exec.js b/lib/exec.js new file mode 100644 index 00000000..cc2f6749 --- /dev/null +++ b/lib/exec.js @@ -0,0 +1,68 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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.Exec = void 0; +const core = __importStar(require("@actions/core")); +const exec = __importStar(require("@actions/exec")); +class Exec { + static exec(commandLine, args, options) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Exec.exec: ${commandLine} ${args === null || args === void 0 ? void 0 : args.join(' ')}`); + return exec.exec(commandLine, args, options); + }); + } + static getExecOutput(commandLine, args, options) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Exec.getExecOutput: ${commandLine} ${args === null || args === void 0 ? void 0 : args.join(' ')}`); + return exec.getExecOutput(commandLine, args, options); + }); + } +} +exports.Exec = Exec; +//# sourceMappingURL=exec.js.map \ No newline at end of file diff --git a/lib/exec.js.map b/lib/exec.js.map new file mode 100644 index 00000000..f787566b --- /dev/null +++ b/lib/exec.js.map @@ -0,0 +1 @@ +{"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAAsC;AACtC,oDAAsC;AAGtC,MAAa,IAAI;IACR,MAAM,CAAO,IAAI,CAAC,WAAmB,EAAE,IAAe,EAAE,OAAqB;;YAClF,IAAI,CAAC,KAAK,CAAC,cAAc,WAAW,IAAI,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC3D,OAAO,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAC/C,CAAC;KAAA;IAEM,MAAM,CAAO,aAAa,CAAC,WAAmB,EAAE,IAAe,EAAE,OAAqB;;YAC3F,IAAI,CAAC,KAAK,CAAC,uBAAuB,WAAW,IAAI,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpE,OAAO,IAAI,CAAC,aAAa,CAAC,WAAW,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QACxD,CAAC;KAAA;CACF;AAVD,oBAUC"} \ No newline at end of file diff --git a/lib/git.d.ts b/lib/git.d.ts new file mode 100644 index 00000000..c33fdc10 --- /dev/null +++ b/lib/git.d.ts @@ -0,0 +1,29 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Context as GitContext } from './types/git'; +export declare class Git { + static context(): Promise; + static isInsideWorkTree(): Promise; + static remoteSha(repo: string, ref: string, token?: string): Promise; + static remoteURL(): Promise; + static ref(): Promise; + static fullCommit(): Promise; + static shortCommit(): Promise; + static tag(): Promise; + private static isHeadDetached; + private static getDetachedRef; + private static exec; +} diff --git a/lib/git.js b/lib/git.js new file mode 100644 index 00000000..28f168c4 --- /dev/null +++ b/lib/git.js @@ -0,0 +1,201 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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.Git = void 0; +const core = __importStar(require("@actions/core")); +const core_1 = require("@octokit/core"); +const plugin_rest_endpoint_methods_1 = require("@octokit/plugin-rest-endpoint-methods"); +const exec_1 = require("./exec"); +const github_1 = require("./github"); +const context_1 = require("@actions/github/lib/context"); +class Git { + static context() { + return __awaiter(this, void 0, void 0, function* () { + const ctx = new context_1.Context(); + ctx.ref = yield Git.ref(); + ctx.sha = yield Git.fullCommit(); + return ctx; + }); + } + static isInsideWorkTree() { + return __awaiter(this, void 0, void 0, function* () { + return yield Git.exec(['rev-parse', '--is-inside-work-tree']) + .then(out => { + return out === 'true'; + }) + .catch(() => { + return false; + }); + }); + } + static remoteSha(repo, ref, token) { + return __awaiter(this, void 0, void 0, function* () { + const repoMatch = repo.match(/github.com\/([^/]+)\/([^/]+?)(?:\.git)?(\/|$)/); + // if we have a token and this is a GitHub repo we can use the GitHub API + if (token && repoMatch) { + core.setSecret(token); + const octokit = new (core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods).defaults({ + baseUrl: github_1.GitHub.apiURL + }))({ auth: token }); + const [owner, repoName] = repoMatch.slice(1, 3); + try { + return (yield octokit.rest.repos.listCommits({ + owner: owner, + repo: repoName, + sha: ref, + per_page: 1 + })).data[0].sha; + } + catch (e) { + throw new Error(`Cannot find remote ref for ${repo}#${ref}: ${e.message}`); + } + } + // otherwise we fall back to git ls-remote + return yield Git.exec(['ls-remote', repo, ref]).then(out => { + const [rsha] = out.split(/[\s\t]/); + if (rsha.length == 0) { + throw new Error(`Cannot find remote ref for ${repo}#${ref}`); + } + return rsha; + }); + }); + } + static remoteURL() { + return __awaiter(this, void 0, void 0, function* () { + return yield Git.exec(['remote', 'get-url', 'origin']).then(rurl => { + if (rurl.length == 0) { + return Git.exec(['remote', 'get-url', 'upstream']).then(rurl => { + if (rurl.length == 0) { + throw new Error(`Cannot find remote URL for origin or upstream`); + } + return rurl; + }); + } + return rurl; + }); + }); + } + static ref() { + return __awaiter(this, void 0, void 0, function* () { + const isHeadDetached = yield Git.isHeadDetached(); + if (isHeadDetached) { + return yield Git.getDetachedRef(); + } + return yield Git.exec(['symbolic-ref', 'HEAD']); + }); + } + static fullCommit() { + return __awaiter(this, void 0, void 0, function* () { + return yield Git.exec(['show', '--format=%H', 'HEAD', '--quiet', '--']); + }); + } + static shortCommit() { + return __awaiter(this, void 0, void 0, function* () { + return yield Git.exec(['show', '--format=%h', 'HEAD', '--quiet', '--']); + }); + } + static tag() { + return __awaiter(this, void 0, void 0, function* () { + return yield Git.exec(['tag', '--points-at', 'HEAD', '--sort', '-version:creatordate']).then(tags => { + if (tags.length == 0) { + return Git.exec(['describe', '--tags', '--abbrev=0']); + } + return tags.split('\n')[0]; + }); + }); + } + static isHeadDetached() { + return __awaiter(this, void 0, void 0, function* () { + return yield Git.exec(['branch', '--show-current']).then(res => { + return res.length == 0; + }); + }); + } + static getDetachedRef() { + return __awaiter(this, void 0, void 0, function* () { + const res = yield Git.exec(['show', '-s', '--pretty=%D']); + // Can be "HEAD, " or "grafted, HEAD, " + const refMatch = res.match(/^(grafted, )?HEAD, (.*)$/); + if (!refMatch || !refMatch[2]) { + throw new Error(`Cannot find detached HEAD ref in "${res}"`); + } + const ref = refMatch[2].trim(); + // Tag refs are formatted as "tag: " + if (ref.startsWith('tag: ')) { + return `refs/tags/${ref.split(':')[1].trim()}`; + } + // Branch refs are formatted as "/, " + const branchMatch = ref.match(/^[^/]+\/[^/]+, (.+)$/); + if (branchMatch) { + return `refs/heads/${branchMatch[1].trim()}`; + } + // Pull request merge refs are formatted as "pull//" + const prMatch = ref.match(/^pull\/\d+\/(head|merge)$/); + if (prMatch) { + return `refs/${ref}`; + } + throw new Error(`Unsupported detached HEAD ref in "${res}"`); + }); + } + static exec() { + return __awaiter(this, arguments, void 0, function* (args = []) { + return yield exec_1.Exec.getExecOutput(`git`, args, { + ignoreReturnCode: true, + silent: true + }).then(res => { + if (res.stderr.length > 0 && res.exitCode != 0) { + throw new Error(res.stderr); + } + return res.stdout.trim(); + }); + }); + } +} +exports.Git = Git; +//# sourceMappingURL=git.js.map \ No newline at end of file diff --git a/lib/git.js.map b/lib/git.js.map new file mode 100644 index 00000000..8531c3ae --- /dev/null +++ b/lib/git.js.map @@ -0,0 +1 @@ +{"version":3,"file":"git.js","sourceRoot":"","sources":["../src/git.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAAsC;AACtC,wCAAsC;AACtC,wFAA0E;AAE1E,iCAA4B;AAC5B,qCAAgC;AAChC,yDAAoD;AAIpD,MAAa,GAAG;IACP,MAAM,CAAO,OAAO;;YACzB,MAAM,GAAG,GAAG,IAAI,iBAAO,EAAE,CAAC;YAC1B,GAAG,CA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3C,gBAAgB,EAAE,IAAI;gBACtB,MAAM,EAAE,IAAI;aACb,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;gBACZ,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,GAAG,CAAC,QAAQ,IAAI,CAAC,EAAE,CAAC;oBAC/C,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBAC9B,CAAC;gBACD,OAAO,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;YAC3B,CAAC,CAAC,CAAC;QACL,CAAC;KAAA;CACF;AA3ID,kBA2IC"} \ No newline at end of file diff --git a/lib/github.d.ts b/lib/github.d.ts new file mode 100644 index 00000000..78880189 --- /dev/null +++ b/lib/github.d.ts @@ -0,0 +1,37 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GitHub as Octokit } from '@actions/github/lib/utils'; +import { Context } from '@actions/github/lib/context'; +import { BuildSummaryOpts, GitHubActionsRuntimeToken, GitHubRepo, UploadArtifactOpts, UploadArtifactResponse } from './types/github'; +export interface GitHubOpts { + token?: string; +} +export declare class GitHub { + readonly octokit: InstanceType; + constructor(opts?: GitHubOpts); + repoData(): Promise; + static get context(): Context; + static get serverURL(): string; + static get apiURL(): string; + static get repository(): string; + static get runId(): number; + static get runAttempt(): number; + static workflowRunURL(setAttempts?: boolean): string; + static get actionsRuntimeToken(): GitHubActionsRuntimeToken | undefined; + static printActionsRuntimeTokenACs(): Promise; + static uploadArtifact(opts: UploadArtifactOpts): Promise; + static writeBuildSummary(opts: BuildSummaryOpts): Promise; +} diff --git a/lib/github.js b/lib/github.js new file mode 100644 index 00000000..053c0330 --- /dev/null +++ b/lib/github.js @@ -0,0 +1,296 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GitHub = void 0; +const crypto_1 = __importDefault(require("crypto")); +const fs_1 = __importDefault(require("fs")); +const js_yaml_1 = __importDefault(require("js-yaml")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +const generated_1 = require("@actions/artifact/lib/generated"); +const artifact_twirp_client_1 = require("@actions/artifact/lib/internal/shared/artifact-twirp-client"); +const util_1 = require("@actions/artifact/lib/internal/shared/util"); +const retention_1 = require("@actions/artifact/lib/internal/upload/retention"); +const artifact_1 = require("@actions/artifact"); +const core = __importStar(require("@actions/core")); +const github = __importStar(require("@actions/github")); +const storage_blob_1 = require("@azure/storage-blob"); +const jwt_decode_1 = require("jwt-decode"); +const util_2 = require("./util"); +class GitHub { + constructor(opts) { + this.octokit = github.getOctokit(`${opts === null || opts === void 0 ? void 0 : opts.token}`); + } + repoData() { + return this.octokit.rest.repos.get(Object.assign({}, github.context.repo)).then(response => response.data); + } + static get context() { + return github.context; + } + static get serverURL() { + return process.env.GITHUB_SERVER_URL || 'https://github.com'; + } + static get apiURL() { + return process.env.GITHUB_API_URL || 'https://api.github.com'; + } + static get repository() { + return `${github.context.repo.owner}/${github.context.repo.repo}`; + } + static get runId() { + return process.env.GITHUB_RUN_ID ? +process.env.GITHUB_RUN_ID : github.context.runId; + } + static get runAttempt() { + // TODO: runAttempt is not yet part of github.context but will be in a + // future release of @actions/github package: https://github.com/actions/toolkit/commit/faa425440f86f9c16587a19dfb59491253a2c92a + return process.env.GITHUB_RUN_ATTEMPT ? +process.env.GITHUB_RUN_ATTEMPT : 1; + } + static workflowRunURL(setAttempts) { + return `${GitHub.serverURL}/${GitHub.repository}/actions/runs/${GitHub.runId}${setAttempts ? `/attempts/${GitHub.runAttempt}` : ''}`; + } + static get actionsRuntimeToken() { + const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; + return token ? (0, jwt_decode_1.jwtDecode)(token) : undefined; + } + static printActionsRuntimeTokenACs() { + return __awaiter(this, void 0, void 0, function* () { + let jwt; + try { + jwt = GitHub.actionsRuntimeToken; + } + catch (e) { + throw new Error(`Cannot parse GitHub Actions Runtime Token: ${e.message}`); + } + if (!jwt) { + throw new Error(`ACTIONS_RUNTIME_TOKEN not set`); + } + try { + JSON.parse(`${jwt.ac}`).forEach(ac => { + let permission; + switch (ac.Permission) { + case 1: + permission = 'read'; + break; + case 2: + permission = 'write'; + break; + case 3: + permission = 'read/write'; + break; + default: + permission = `unimplemented (${ac.Permission})`; + } + core.info(`${ac.Scope}: ${permission}`); + }); + } + catch (e) { + throw new Error(`Cannot parse GitHub Actions Runtime Token ACs: ${e.message}`); + } + }); + } + static uploadArtifact(opts) { + return __awaiter(this, void 0, void 0, function* () { + const artifactName = path_1.default.basename(opts.filename); + const backendIds = (0, util_1.getBackendIdsFromToken)(); + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + core.info(`Uploading ${artifactName} to blob storage`); + const createArtifactReq = { + workflowRunBackendId: backendIds.workflowRunBackendId, + workflowJobRunBackendId: backendIds.workflowJobRunBackendId, + name: artifactName, + version: 4 + }; + const expiresAt = (0, retention_1.getExpiration)(opts === null || opts === void 0 ? void 0 : opts.retentionDays); + if (expiresAt) { + createArtifactReq.expiresAt = expiresAt; + } + const createArtifactResp = yield artifactClient.CreateArtifact(createArtifactReq); + if (!createArtifactResp.ok) { + throw new artifact_1.InvalidResponseError('cannot create artifact client'); + } + let uploadByteCount = 0; + const blobClient = new storage_blob_1.BlobClient(createArtifactResp.signedUploadUrl); + const blockBlobClient = blobClient.getBlockBlobClient(); + const headers = { + blobContentDisposition: `attachment; filename="${artifactName}"` + }; + if (opts.mimeType) { + headers.blobContentType = opts.mimeType; + } + core.debug(`Upload headers: ${JSON.stringify(headers)}`); + try { + core.info('Beginning upload of artifact content to blob storage'); + yield blockBlobClient.uploadFile(opts.filename, { + blobHTTPHeaders: headers, + onProgress: (progress) => { + core.info(`Uploaded bytes ${progress.loadedBytes}`); + uploadByteCount = progress.loadedBytes; + } + }); + } + catch (error) { + if (artifact_1.NetworkError.isNetworkErrorCode(error === null || error === void 0 ? void 0 : error.code)) { + throw new artifact_1.NetworkError(error === null || error === void 0 ? void 0 : error.code); + } + throw error; + } + core.info('Finished uploading artifact content to blob storage!'); + const sha256Hash = crypto_1.default.createHash('sha256').update(fs_1.default.readFileSync(opts.filename)).digest('hex'); + core.info(`SHA256 hash of uploaded artifact is ${sha256Hash}`); + const finalizeArtifactReq = { + workflowRunBackendId: backendIds.workflowRunBackendId, + workflowJobRunBackendId: backendIds.workflowJobRunBackendId, + name: artifactName, + size: uploadByteCount ? uploadByteCount.toString() : '0' + }; + if (sha256Hash) { + finalizeArtifactReq.hash = generated_1.StringValue.create({ + value: `sha256:${sha256Hash}` + }); + } + core.info(`Finalizing artifact upload`); + const finalizeArtifactResp = yield artifactClient.FinalizeArtifact(finalizeArtifactReq); + if (!finalizeArtifactResp.ok) { + throw new artifact_1.InvalidResponseError('Cannot finalize artifact upload'); + } + const artifactId = BigInt(finalizeArtifactResp.artifactId); + core.info(`Artifact successfully finalized (${artifactId})`); + const artifactURL = `${GitHub.workflowRunURL()}/artifacts/${artifactId}`; + core.info(`Artifact download URL: ${artifactURL}`); + return { + id: Number(artifactId), + filename: artifactName, + size: uploadByteCount, + url: artifactURL + }; + }); + } + static writeBuildSummary(opts) { + return __awaiter(this, void 0, void 0, function* () { + // can't use original core.summary.addLink due to the need to make + // EOL optional + const addLink = function (text, url, addEOL = false) { + return `${text}` + (addEOL ? os_1.default.EOL : ''); + }; + const refsSize = Object.keys(opts.exportRes.refs).length; + // we just need the last two parts of the URL as they are always relative + // to the workflow run URL otherwise URL could be broken if GitHub + // repository name is part of a secret value used in the workflow. e.g.: + // artifact: https://github.com/docker/actions-toolkit/actions/runs/9552208295/artifacts/1609622746 + // workflow: https://github.com/docker/actions-toolkit/actions/runs/9552208295 + // https://github.com/docker/actions-toolkit/issues/367 + const artifactRelativeURL = `./${GitHub.runId}/${opts.uploadRes.url.split('/').slice(-2).join('/')}`; + // prettier-ignore + const sum = core.summary + .addHeading('Docker Build summary', 1) + .addRaw(`

`) + .addRaw(`For a detailed look at the build, download the following build record archive and import it into Docker Desktop's Builds view. `) + .addBreak() + .addRaw(`Build records include details such as timing, dependencies, results, logs, traces, and other information about a build. `) + .addRaw(addLink('Learn more', 'https://docs.docker.com/go/build-summary/')) + .addRaw('

') + .addRaw(`

`) + .addRaw(`:arrow_down: ${addLink(`${util_2.Util.stringToUnicodeEntities(opts.uploadRes.filename)}`, artifactRelativeURL)} (${util_2.Util.formatFileSize(opts.uploadRes.size)})`) + .addBreak() + .addRaw(`This file includes ${refsSize} build record${refsSize > 1 ? 's' : ''}.`) + .addRaw(`

`) + .addRaw(`

`) + .addRaw(`Find this useful? `) + .addRaw(addLink('Let us know', 'https://docs.docker.com/feedback/gha-build-summary')) + .addRaw('

'); + sum.addHeading('Preview', 2); + const summaryTableData = [ + [ + { header: true, data: 'ID' }, + { header: true, data: 'Name' }, + { header: true, data: 'Status' }, + { header: true, data: 'Cached' }, + { header: true, data: 'Duration' } + ] + ]; + let summaryError; + for (const ref in opts.exportRes.summaries) { + if (Object.prototype.hasOwnProperty.call(opts.exportRes.summaries, ref)) { + const summary = opts.exportRes.summaries[ref]; + // prettier-ignore + summaryTableData.push([ + { data: `${ref.substring(0, 6).toUpperCase()}` }, + { data: `${summary.name}` }, + { data: `${summary.status === 'completed' ? ':white_check_mark:' : summary.status === 'canceled' ? ':no_entry_sign:' : ':x:'} ${summary.status}` }, + { data: `${summary.numCachedSteps > 0 ? Math.round((summary.numCachedSteps / summary.numTotalSteps) * 100) : 0}%` }, + { data: summary.duration } + ]); + if (summary.error) { + summaryError = summary.error; + } + } + } + sum.addTable([...summaryTableData]); + if (summaryError) { + sum.addHeading('Error', 4); + sum.addCodeBlock(summaryError, 'text'); + } + if (opts.inputs) { + sum.addHeading('Build inputs', 2).addCodeBlock(js_yaml_1.default.dump(opts.inputs, { + indent: 2, + lineWidth: -1 + }), 'yaml'); + } + if (opts.bakeDefinition) { + sum.addHeading('Bake definition', 2).addCodeBlock(JSON.stringify(opts.bakeDefinition, null, 2), 'json'); + } + core.info(`Writing summary`); + yield sum.addSeparator().write(); + }); + } +} +exports.GitHub = GitHub; +//# sourceMappingURL=github.js.map \ No newline at end of file diff --git a/lib/github.js.map b/lib/github.js.map new file mode 100644 index 00000000..86bd7269 --- /dev/null +++ b/lib/github.js.map @@ -0,0 +1 @@ +{"version":3,"file":"github.js","sourceRoot":"","sources":["../src/github.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAA4B;AAC5B,4CAAoB;AACpB,sDAA6B;AAC7B,4CAAoB;AACpB,gDAAwB;AACxB,+DAA4G;AAC5G,uGAAwG;AACxG,qEAAkF;AAClF,+EAA8E;AAC9E,gDAAqE;AACrE,oDAAsC;AAEtC,wDAA0C;AAI1C,sDAAgE;AAChE,2CAAiD;AAEjD,iCAA4B;AAQ5B,MAAa,MAAM;IAGjB,YAAY,IAAiB;QAC3B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,KAAK,EAAE,CAAC,CAAC;IACrD,CAAC;IAEM,QAAQ;QACb,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,mBAAK,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAkB,CAAC,CAAC;IAC7G,CAAC;IAED,MAAM,KAAK,OAAO;QAChB,OAAO,MAAM,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,MAAM,KAAK,SAAS;QAClB,OAAO,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,oBAAoB,CAAC;IAC/D,CAAC;IA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AAG,gBAAgB,CAAC,CAAC,CAAC;YACpC,IAAI,YAAY,EAAE,CAAC;gBACjB,GAAG,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;gBAC3B,GAAG,CAAC,YAAY,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;YACzC,CAAC;YAED,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChB,GAAG,CAAC,UAAU,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC,YAAY,CAC5C,iBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;oBACvB,MAAM,EAAE,CAAC;oBACT,SAAS,EAAE,CAAC,CAAC;iBACd,CAAC,EACF,MAAM,CACP,CAAC;YACJ,CAAC;YAED,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;gBACxB,GAAG,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;YAC1G,CAAC;YAED,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;YAC7B,MAAM,GAAG,CAAC,YAAY,EAAE,CAAC,KAAK,EAAE,CAAC;QACnC,CAAC;KAAA;CACF;AAhQD,wBAgQC"} \ No newline at end of file diff --git a/lib/index.d.ts b/lib/index.d.ts new file mode 100644 index 00000000..72d6b77f --- /dev/null +++ b/lib/index.d.ts @@ -0,0 +1,24 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Runs a GitHub Action. + * Output will be streamed to the live console. + * + * @param main runs the defined function. + * @param post runs the defined function at the end of the job if set. + * @returns Promise + */ +export declare function run(main: () => Promise, post?: () => Promise): Promise; diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 00000000..07b7fe35 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,86 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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.run = void 0; +const core = __importStar(require("@actions/core")); +const cache_1 = require("./cache"); +const isPost = !!process.env['STATE_isPost']; +if (!isPost) { + core.saveState('isPost', 'true'); +} +/** + * Runs a GitHub Action. + * Output will be streamed to the live console. + * + * @param main runs the defined function. + * @param post runs the defined function at the end of the job if set. + * @returns Promise + */ +function run(main, post) { + return __awaiter(this, void 0, void 0, function* () { + if (!isPost) { + try { + yield main(); + } + catch (e) { + core.setFailed(e.message); + } + } + else { + if (post) { + yield post(); + } + yield core.group(`Post cache`, () => __awaiter(this, void 0, void 0, function* () { + yield cache_1.Cache.post(); + })); + } + }); +} +exports.run = run; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/index.js.map b/lib/index.js.map new file mode 100644 index 00000000..2413b130 --- /dev/null +++ b/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAAsC;AAEtC,mCAA8B;AAE9B,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AAC7C,IAAI,CAAC,MAAM,EAAE,CAAC;IACZ,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AACnC,CAAC;AAED;;;;;;;GAOG;AACH,SAAsB,GAAG,CAAC,IAAyB,EAAE,IAA0B;;QAC7E,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,IAAI,CAAC;gBACH,MAAM,IAAI,EAAE,CAAC;YACf,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;aAAM,CAAC;YACN,IAAI,IAAI,EAAE,CAAC;gBACT,MAAM,IAAI,EAAE,CAAC;YACf,CAAC;YACD,MAAM,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,GAAS,EAAE;gBACxC,MAAM,aAAK,CAAC,IAAI,EAAE,CAAC;YACrB,CAAC,CAAA,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CAAA;AAfD,kBAeC"} \ No newline at end of file diff --git a/lib/oci/oci.d.ts b/lib/oci/oci.d.ts new file mode 100644 index 00000000..905e9a9b --- /dev/null +++ b/lib/oci/oci.d.ts @@ -0,0 +1,9 @@ +import { Archive, LoadArchiveOpts } from '../types/oci/oci'; +export declare class OCI { + static loadArchive(opts: LoadArchiveOpts): Promise; + private static isIndex; + private static isManifest; + private static isImage; + private static extractBlob; + private static streamToJson; +} diff --git a/lib/oci/oci.js b/lib/oci/oci.js new file mode 100644 index 00000000..5fbab515 --- /dev/null +++ b/lib/oci/oci.js @@ -0,0 +1,199 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OCI = void 0; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const fs_1 = __importDefault(require("fs")); +const gunzip_maybe_1 = __importDefault(require("gunzip-maybe")); +const path = __importStar(require("path")); +const tar = __importStar(require("tar-stream")); +const layout_1 = require("../types/oci/layout"); +const mediatype_1 = require("../types/oci/mediatype"); +class OCI { + static loadArchive(opts) { + return new Promise((resolve, reject) => { + const tarex = tar.extract(); + let rootIndex; + let rootLayout; + const indexes = {}; + const manifests = {}; + const images = {}; + const blobs = {}; + tarex.on('entry', (header, stream, next) => __awaiter(this, void 0, void 0, function* () { + if (header.type === 'file') { + const filename = path.normalize(header.name); + if (filename === layout_1.IMAGE_INDEX_FILE_V1) { + rootIndex = yield OCI.streamToJson(stream); + } + else if (filename === layout_1.IMAGE_LAYOUT_FILE_V1) { + rootLayout = yield OCI.streamToJson(stream); + } + else if (filename.startsWith(path.join(layout_1.IMAGE_BLOBS_DIR_V1, path.sep))) { + const blob = yield OCI.extractBlob(stream); + const digest = `${filename.split(path.sep)[1]}:${filename.split(path.sep)[filename.split(path.sep).length - 1]}`; + if (OCI.isIndex(blob)) { + indexes[digest] = JSON.parse(blob); + } + else if (OCI.isManifest(blob)) { + manifests[digest] = JSON.parse(blob); + } + else if (OCI.isImage(blob)) { + images[digest] = JSON.parse(blob); + } + else { + blobs[digest] = blob; + } + } + else { + reject(new Error(`Invalid OCI archive: unexpected file ${filename}`)); + } + } + stream.resume(); + next(); + })); + tarex.on('finish', () => { + if (!rootIndex || !rootLayout) { + reject(new Error('Invalid OCI archive: missing index or layout')); + } + resolve({ + root: { + index: rootIndex, + layout: rootLayout + }, + indexes: indexes, + manifests: manifests, + images: images, + blobs: blobs + }); + }); + tarex.on('error', error => { + reject(error); + }); + fs_1.default.createReadStream(opts.file).pipe((0, gunzip_maybe_1.default)()).pipe(tarex); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isIndex(blob) { + try { + const index = JSON.parse(blob); + return index.mediaType === mediatype_1.MEDIATYPE_IMAGE_INDEX_V1; + } + catch (_a) { + return false; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isManifest(blob) { + try { + const manifest = JSON.parse(blob); + return manifest.mediaType === mediatype_1.MEDIATYPE_IMAGE_MANIFEST_V1 && manifest.layers.length > 0; + } + catch (_a) { + return false; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isImage(blob) { + try { + const image = JSON.parse(blob); + return image.rootfs.type !== ''; + } + catch (_a) { + return false; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static extractBlob(stream) { + return new Promise((resolve, reject) => { + const chunks = []; + const dstream = stream.pipe((0, gunzip_maybe_1.default)()); + dstream.on('data', chunk => { + chunks.push(chunk); + }); + dstream.on('end', () => { + resolve(Buffer.concat(chunks).toString('utf8')); + }); + dstream.on('error', (error) => __awaiter(this, void 0, void 0, function* () { + reject(error); + })); + }); + } + static streamToJson(stream) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + const chunks = []; + let bytes = 0; + stream.on('data', chunk => { + bytes += chunk.length; + if (bytes <= 2 * 1024 * 1024) { + chunks.push(chunk.toString('utf8')); + } + else { + reject(new Error('The data stream exceeds the size limit for JSON parsing.')); + } + }); + stream.on('end', () => { + try { + resolve(JSON.parse(chunks.join(''))); + } + catch (error) { + reject(error); + } + }); + stream.on('error', (error) => __awaiter(this, void 0, void 0, function* () { + reject(error); + })); + }); + }); + } +} +exports.OCI = OCI; +//# sourceMappingURL=oci.js.map \ No newline at end of file diff --git a/lib/oci/oci.js.map b/lib/oci/oci.js.map new file mode 100644 index 00000000..714a58bc --- /dev/null +++ b/lib/oci/oci.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oci.js","sourceRoot":"","sources":["../../src/oci/oci.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;GAcG;AACH,4CAAoB;AACpB,gEAAkC;AAClC,2CAA6B;AAE7B,gDAAkC;AAMlC,gDAA+G;AAC/G,sDAA6F;AAE7F,MAAa,GAAG;IACP,MAAM,CAAC,WAAW,CAAC,IAAqB;QAC7C,OAAO,IAAI,OAAO,CAAU,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC9C,MAAM,KAAK,GAAgB,GAAG,CAAC,OAAO,EAAE,CAAC;YAEzC,IAAI,SAAgB,CAAC;YACrB,IAAI,UAAuB,CAAC;YAC5B,MAAM,OAAO,GAA0B,EAAE,CAAC;YAC1C,MAAM,SAAS,GAA6B,EAAE,CAAC;YAC/C,MAAM,MAAM,GAA0B,EAAE,CAAC;YACzC,MAAM,KAAK,GAA4B,EAAE,CAAC;YAE1C,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,CAAO,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE;gBAC/C,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;oBAC3B,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;oB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CAAC,CAAC,CAAC;IACL,CAAC;IAEO,MAAM,CAAO,YAAY,CAAI,MAAgB;;YACnD,OAAO,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACxC,MAAM,MAAM,GAAa,EAAE,CAAC;gBAC5B,IAAI,KAAK,GAAG,CAAC,CAAC;gBACd,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE;oBACxB,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC;oBACtB,IAAI,KAAK,IAAI,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;wBAC7B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;oBACtC,CAAC;yBAAM,CAAC;wBACN,MAAM,CAAC,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC,CAAC;oBAChF,CAAC;gBACH,CAAC,CAAC,CAAC;gBACH,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;oBACpB,IAAI,CAAC;wBACH,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;oBACvC,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBACf,MAAM,CAAC,KAAK,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC,CAAC,CAAC;gBACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAM,KAAK,EAAC,EAAE;oBAC/B,MAAM,CAAC,KAAK,CAAC,CAAC;gBAChB,CAAC,CAAA,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;KAAA;CACF;AAtID,kBAsIC"} \ No newline at end of file diff --git a/lib/toolkit.d.ts b/lib/toolkit.d.ts new file mode 100644 index 00000000..e96787d4 --- /dev/null +++ b/lib/toolkit.d.ts @@ -0,0 +1,39 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Buildx } from './buildx/buildx'; +import { Build as BuildxBuild } from './buildx/build'; +import { Bake as BuildxBake } from './buildx/bake'; +import { Install as BuildxInstall } from './buildx/install'; +import { Builder } from './buildx/builder'; +import { BuildKit } from './buildkit/buildkit'; +import { GitHub } from './github'; +export interface ToolkitOpts { + /** + * GitHub token to use for authentication. + * Uses `process.env.GITHUB_TOKEN` by default. + */ + githubToken?: string; +} +export declare class Toolkit { + github: GitHub; + buildx: Buildx; + buildxBuild: BuildxBuild; + buildxBake: BuildxBake; + buildxInstall: BuildxInstall; + builder: Builder; + buildkit: BuildKit; + constructor(opts?: ToolkitOpts); +} diff --git a/lib/toolkit.js b/lib/toolkit.js new file mode 100644 index 00000000..7c134de3 --- /dev/null +++ b/lib/toolkit.js @@ -0,0 +1,38 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Toolkit = void 0; +const buildx_1 = require("./buildx/buildx"); +const build_1 = require("./buildx/build"); +const bake_1 = require("./buildx/bake"); +const install_1 = require("./buildx/install"); +const builder_1 = require("./buildx/builder"); +const buildkit_1 = require("./buildkit/buildkit"); +const github_1 = require("./github"); +class Toolkit { + constructor(opts = {}) { + this.github = new github_1.GitHub({ token: opts.githubToken }); + this.buildx = new buildx_1.Buildx(); + this.buildxBuild = new build_1.Build({ buildx: this.buildx }); + this.buildxBake = new bake_1.Bake({ buildx: this.buildx }); + this.buildxInstall = new install_1.Install(); + this.builder = new builder_1.Builder({ buildx: this.buildx }); + this.buildkit = new buildkit_1.BuildKit({ buildx: this.buildx }); + } +} +exports.Toolkit = Toolkit; +//# sourceMappingURL=toolkit.js.map \ No newline at end of file diff --git a/lib/toolkit.js.map b/lib/toolkit.js.map new file mode 100644 index 00000000..9a4370fd --- /dev/null +++ b/lib/toolkit.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolkit.js","sourceRoot":"","sources":["../src/toolkit.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAAuC;AACvC,0CAAoD;AACpD,wCAAiD;AACjD,8CAA0D;AAC1D,8CAAyC;AACzC,kDAA6C;AAC7C,qCAAgC;AAUhC,MAAa,OAAO;IASlB,YAAY,OAAoB,EAAE;QAChC,IAAI,CAAC,MAAM,GAAG,IAAI,eAAM,CAAC,EAAC,KAAK,EAAE,IAAI,CAAC,WAAW,EAAC,CAAC,CAAC;QACpD,IAAI,CAAC,MAAM,GAAG,IAAI,eAAM,EAAE,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,aAAW,CAAC,EAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAC,CAAC,CAAC;QAC1D,IAAI,CAAC,UAAU,GAAG,IAAI,WAAU,CAAC,EAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAC,CAAC,CAAC;QACxD,IAAI,CAAC,aAAa,GAAG,IAAI,iBAAa,EAAE,CAAC;QACzC,IAAI,CAAC,OAAO,GAAG,IAAI,iBAAO,CAAC,EAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAC,CAAC,CAAC;QAClD,IAAI,CAAC,QAAQ,GAAG,IAAI,mBAAQ,CAAC,EAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAC,CAAC,CAAC;IACtD,CAAC;CACF;AAlBD,0BAkBC"} \ No newline at end of file diff --git a/lib/types/buildkit/buildkit.d.ts b/lib/types/buildkit/buildkit.d.ts new file mode 100644 index 00000000..0de1e714 --- /dev/null +++ b/lib/types/buildkit/buildkit.d.ts @@ -0,0 +1,16 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const MEDIATYPE_STATUS_V0 = "application/vnd.buildkit.status.v0"; diff --git a/lib/types/buildkit/buildkit.js b/lib/types/buildkit/buildkit.js new file mode 100644 index 00000000..acc7571c --- /dev/null +++ b/lib/types/buildkit/buildkit.js @@ -0,0 +1,21 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MEDIATYPE_STATUS_V0 = void 0; +// https://github.com/moby/buildkit/blob/v0.14.0/solver/llbsolver/history.go#L672 +exports.MEDIATYPE_STATUS_V0 = 'application/vnd.buildkit.status.v0'; +//# sourceMappingURL=buildkit.js.map \ No newline at end of file diff --git a/lib/types/buildkit/buildkit.js.map b/lib/types/buildkit/buildkit.js.map new file mode 100644 index 00000000..676dfd34 --- /dev/null +++ b/lib/types/buildkit/buildkit.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buildkit.js","sourceRoot":"","sources":["../../../src/types/buildkit/buildkit.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,iFAAiF;AACpE,QAAA,mBAAmB,GAAG,oCAAoC,CAAC"} \ No newline at end of file diff --git a/lib/types/buildkit/client.d.ts b/lib/types/buildkit/client.d.ts new file mode 100644 index 00000000..1ba95038 --- /dev/null +++ b/lib/types/buildkit/client.d.ts @@ -0,0 +1,61 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Digest } from '../oci/digest'; +import { ProgressGroup, Range, SourceInfo } from './ops'; +export interface Vertex { + digest?: Digest; + inputs?: Array; + name?: string; + started?: Date; + completed?: Date; + cached?: boolean; + error?: string; + progressGroup?: ProgressGroup; +} +export interface VertexStatus { + id: string; + vertex?: Digest; + name?: string; + total?: number; + current: number; + timestamp?: Date; + started?: Date; + completed?: Date; +} +export interface VertexLog { + vertex?: Digest; + stream?: number; + data: any; + timestamp: Date; +} +export interface VertexWarning { + vertex?: Digest; + level?: number; + short?: any; + detail?: Array; + url?: string; + sourceInfo?: SourceInfo; + range?: Array; +} +export interface SolveStatus { + vertexes?: Array; + statuses?: Array; + logs?: Array; + warnings?: Array; +} +export interface SolveResponse { + exporterResponse: Record; +} diff --git a/lib/types/buildkit/client.js b/lib/types/buildkit/client.js new file mode 100644 index 00000000..0b4b3566 --- /dev/null +++ b/lib/types/buildkit/client.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/lib/types/buildkit/client.js.map b/lib/types/buildkit/client.js.map new file mode 100644 index 00000000..28a2280b --- /dev/null +++ b/lib/types/buildkit/client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/types/buildkit/client.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/buildkit/control.d.ts b/lib/types/buildkit/control.d.ts new file mode 100644 index 00000000..a86196a5 --- /dev/null +++ b/lib/types/buildkit/control.d.ts @@ -0,0 +1,88 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Descriptor } from '../oci/descriptor'; +import { Digest } from '../oci/digest'; +import { ProgressGroup, Range, SourceInfo } from './ops'; +import { RpcStatus } from './rpc'; +export interface BuildHistoryRecord { + Ref: string; + Frontend: string; + FrontendAttrs: Record; + Exporters: Array; + error?: RpcStatus; + CreatedAt?: Date; + CompletedAt?: Date; + logs?: Descriptor; + ExporterResponse: Record; + Result?: BuildResultInfo; + Results: Record; + Generation: number; + trace?: Descriptor; + pinned: boolean; + numCachedSteps: number; + numTotalSteps: number; + numCompletedSteps: number; +} +export interface Exporter { + Type: string; + Attrs: Record; +} +export interface BuildResultInfo { + ResultDeprecated?: Descriptor; + Attestations?: Array; + Results?: Record; +} +export interface StatusResponse { + vertexes?: Array; + statuses?: Array; + logs?: Array; + warnings?: Array; +} +export interface Vertex { + digest: Digest; + inputs: Array; + name?: string; + cached?: boolean; + started?: Date; + completed?: Date; + error?: string; + progressGroup?: ProgressGroup; +} +export interface VertexStatus { + ID?: string; + vertex: Digest; + name?: string; + current?: number; + total?: number; + timestamp: Date; + started?: Date; + completed?: Date; +} +export interface VertexLog { + vertex: Digest; + timestamp: Date; + stream?: number; + msg?: any; +} +export interface VertexWarning { + vertex: Digest; + level?: number; + short?: any; + detail?: Array; + url?: string; + info?: SourceInfo; + ranges?: Array; +} diff --git a/lib/types/buildkit/control.js b/lib/types/buildkit/control.js new file mode 100644 index 00000000..9ad5d4df --- /dev/null +++ b/lib/types/buildkit/control.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=control.js.map \ No newline at end of file diff --git a/lib/types/buildkit/control.js.map b/lib/types/buildkit/control.js.map new file mode 100644 index 00000000..77954713 --- /dev/null +++ b/lib/types/buildkit/control.js.map @@ -0,0 +1 @@ +{"version":3,"file":"control.js","sourceRoot":"","sources":["../../../src/types/buildkit/control.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/buildkit/ops.d.ts b/lib/types/buildkit/ops.d.ts new file mode 100644 index 00000000..f0ceab7e --- /dev/null +++ b/lib/types/buildkit/ops.d.ts @@ -0,0 +1,60 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Definition { + def?: Array; + metadata: Record; + Source?: Source; +} +export interface OpMetadata { + ignore_cache?: boolean; + description?: Record; + export_cache?: ExportCache; + caps: Record; + progress_group?: ProgressGroup; +} +export interface Source { + locations?: Record; + infos?: Array; +} +export interface Locations { + locations?: Array; +} +export interface Location { + sourceIndex?: number; + ranges?: Array; +} +export interface Range { + start: Position; + end: Position; +} +export interface Position { + line: number; + character: number; +} +export interface SourceInfo { + filename?: string; + data?: any; + definition?: Definition; + language?: string; +} +export interface ExportCache { + Value?: boolean; +} +export interface ProgressGroup { + id?: string; + name?: string; + weak?: boolean; +} diff --git a/lib/types/buildkit/ops.js b/lib/types/buildkit/ops.js new file mode 100644 index 00000000..3556b334 --- /dev/null +++ b/lib/types/buildkit/ops.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ops.js.map \ No newline at end of file diff --git a/lib/types/buildkit/ops.js.map b/lib/types/buildkit/ops.js.map new file mode 100644 index 00000000..f8cacec1 --- /dev/null +++ b/lib/types/buildkit/ops.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ops.js","sourceRoot":"","sources":["../../../src/types/buildkit/ops.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/buildkit/rpc.d.ts b/lib/types/buildkit/rpc.d.ts new file mode 100644 index 00000000..64fe4cf6 --- /dev/null +++ b/lib/types/buildkit/rpc.d.ts @@ -0,0 +1,24 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface RpcStatus { + code: number; + message: string; + details: Array; +} +export interface RpcAny { + type_url: string; + value: any; +} diff --git a/lib/types/buildkit/rpc.js b/lib/types/buildkit/rpc.js new file mode 100644 index 00000000..ea2a0a3d --- /dev/null +++ b/lib/types/buildkit/rpc.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=rpc.js.map \ No newline at end of file diff --git a/lib/types/buildkit/rpc.js.map b/lib/types/buildkit/rpc.js.map new file mode 100644 index 00000000..45b6b202 --- /dev/null +++ b/lib/types/buildkit/rpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../../src/types/buildkit/rpc.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/buildx/bake.d.ts b/lib/types/buildx/bake.d.ts new file mode 100644 index 00000000..e3735f60 --- /dev/null +++ b/lib/types/buildx/bake.d.ts @@ -0,0 +1,47 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface BakeDefinition { + group: Record; + target: Record; +} +export interface BakeMetadata { + [target: string]: Record; +} +export interface Group { + targets: Array; +} +export interface Target { + args?: Record; + attest?: Array; + 'cache-from'?: Array; + 'cache-to'?: Array; + context: string; + contexts?: Record; + dockerfile: string; + 'dockerfile-inline'?: string; + labels?: Record; + 'no-cache'?: boolean; + 'no-cache-filter'?: Array; + output?: Array; + platforms?: Array; + pull?: boolean; + secret?: Array; + 'shm-size'?: string; + ssh?: Array; + tags?: Array; + target?: string; + ulimits?: Array; +} diff --git a/lib/types/buildx/bake.js b/lib/types/buildx/bake.js new file mode 100644 index 00000000..a3cf9bb6 --- /dev/null +++ b/lib/types/buildx/bake.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=bake.js.map \ No newline at end of file diff --git a/lib/types/buildx/bake.js.map b/lib/types/buildx/bake.js.map new file mode 100644 index 00000000..045dc989 --- /dev/null +++ b/lib/types/buildx/bake.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bake.js","sourceRoot":"","sources":["../../../src/types/buildx/bake.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/buildx/build.d.ts b/lib/types/buildx/build.d.ts new file mode 100644 index 00000000..b386c4f3 --- /dev/null +++ b/lib/types/buildx/build.d.ts @@ -0,0 +1,18 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type BuildMetadata = { + [key: string]: any; +}; diff --git a/lib/types/buildx/build.js b/lib/types/buildx/build.js new file mode 100644 index 00000000..7d406840 --- /dev/null +++ b/lib/types/buildx/build.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=build.js.map \ No newline at end of file diff --git a/lib/types/buildx/build.js.map b/lib/types/buildx/build.js.map new file mode 100644 index 00000000..4c6cb5da --- /dev/null +++ b/lib/types/buildx/build.js.map @@ -0,0 +1 @@ +{"version":3,"file":"build.js","sourceRoot":"","sources":["../../../src/types/buildx/build.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/buildx/builder.d.ts b/lib/types/buildx/builder.d.ts new file mode 100644 index 00000000..584fb074 --- /dev/null +++ b/lib/types/buildx/builder.d.ts @@ -0,0 +1,41 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface BuilderInfo { + name?: string; + driver?: string; + lastActivity?: Date; + nodes: NodeInfo[]; +} +export interface Node { + name?: string; + endpoint?: string; + 'driver-opts'?: Array; + 'buildkitd-flags'?: string; + platforms?: string; +} +export interface NodeInfo extends Node { + status?: string; + buildkit?: string; + features?: Record; + labels?: Record; + gcPolicy?: Array; +} +export interface GCPolicy { + all?: boolean; + filter?: string[]; + keepDuration?: string; + keepBytes?: string; +} diff --git a/lib/types/buildx/builder.js b/lib/types/buildx/builder.js new file mode 100644 index 00000000..db3ce450 --- /dev/null +++ b/lib/types/buildx/builder.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=builder.js.map \ No newline at end of file diff --git a/lib/types/buildx/builder.js.map b/lib/types/buildx/builder.js.map new file mode 100644 index 00000000..a186dac8 --- /dev/null +++ b/lib/types/buildx/builder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../src/types/buildx/builder.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/buildx/buildx.d.ts b/lib/types/buildx/buildx.d.ts new file mode 100644 index 00000000..9c10cdac --- /dev/null +++ b/lib/types/buildx/buildx.d.ts @@ -0,0 +1,41 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Cert { + cacert?: string; + cert?: string; + key?: string; +} +export interface DownloadVersion { + key: string; + version: string; + downloadURL: string; + releasesURL: string; +} +export interface LocalRefsOpts { + dir: string; + builderName?: string; + nodeName?: string; + since?: Date; +} +export interface LocalRefsResponse { + [ref: string]: LocalState; +} +export interface LocalState { + Target: string; + LocalPath: string; + DockerfilePath: string; + GroupRef?: string; +} diff --git a/lib/types/buildx/buildx.js b/lib/types/buildx/buildx.js new file mode 100644 index 00000000..e687c1f9 --- /dev/null +++ b/lib/types/buildx/buildx.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=buildx.js.map \ No newline at end of file diff --git a/lib/types/buildx/buildx.js.map b/lib/types/buildx/buildx.js.map new file mode 100644 index 00000000..9061984c --- /dev/null +++ b/lib/types/buildx/buildx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buildx.js","sourceRoot":"","sources":["../../../src/types/buildx/buildx.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/buildx/history.d.ts b/lib/types/buildx/history.d.ts new file mode 100644 index 00000000..7a14ab5c --- /dev/null +++ b/lib/types/buildx/history.d.ts @@ -0,0 +1,40 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface ExportRecordOpts { + refs: Array; + image?: string; +} +export interface ExportRecordResponse { + dockerbuildFilename: string; + dockerbuildSize: number; + summaries: Summaries; + builderName: string; + nodeName: string; + refs: Array; +} +export interface Summaries { + [ref: string]: RecordSummary; +} +export interface RecordSummary { + name: string; + status: string; + duration: string; + numCachedSteps: number; + numTotalSteps: number; + numCompletedSteps: number; + frontendAttrs: Record; + error?: string; +} diff --git a/lib/types/buildx/history.js b/lib/types/buildx/history.js new file mode 100644 index 00000000..46547d43 --- /dev/null +++ b/lib/types/buildx/history.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=history.js.map \ No newline at end of file diff --git a/lib/types/buildx/history.js.map b/lib/types/buildx/history.js.map new file mode 100644 index 00000000..2bd9471f --- /dev/null +++ b/lib/types/buildx/history.js.map @@ -0,0 +1 @@ +{"version":3,"file":"history.js","sourceRoot":"","sources":["../../../src/types/buildx/history.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/docker/docker.d.ts b/lib/types/docker/docker.d.ts new file mode 100644 index 00000000..90c1da64 --- /dev/null +++ b/lib/types/docker/docker.d.ts @@ -0,0 +1,61 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface ConfigFile { + auths: Record; + HttpHeaders?: Record; + psFormat?: string; + imagesFormat?: string; + networksFormat?: string; + pluginsFormat?: string; + volumesFormat?: string; + statsFormat?: string; + detachKeys?: string; + credsStore?: string; + credHelpers?: Record; + serviceInspectFormat?: string; + servicesFormat?: string; + tasksFormat?: string; + secretFormat?: string; + configFormat?: string; + nodesFormat?: string; + pruneFilters?: string[]; + proxies?: Record; + experimental?: string; + stackOrchestrator?: string; + kubernetes?: KubernetesConfig; + currentContext?: string; + cliPluginsExtraDirs?: string[]; + plugins?: Record>; + aliases?: Record; +} +export interface ProxyConfig { + httpProxy?: string; + httpsProxy?: string; + noProxy?: string; + ftpProxy?: string; +} +export interface KubernetesConfig { + allNamespaces?: string; +} +export interface AuthConfig { + username?: string; + password?: string; + auth?: string; + email?: string; + serveraddress?: string; + identitytoken?: string; + registrytoken?: string; +} diff --git a/lib/types/docker/docker.js b/lib/types/docker/docker.js new file mode 100644 index 00000000..94c81ca9 --- /dev/null +++ b/lib/types/docker/docker.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=docker.js.map \ No newline at end of file diff --git a/lib/types/docker/docker.js.map b/lib/types/docker/docker.js.map new file mode 100644 index 00000000..cd8f9be8 --- /dev/null +++ b/lib/types/docker/docker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"docker.js","sourceRoot":"","sources":["../../../src/types/docker/docker.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/dockerhub.d.ts b/lib/types/dockerhub.d.ts new file mode 100644 index 00000000..c456400d --- /dev/null +++ b/lib/types/dockerhub.d.ts @@ -0,0 +1,104 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface TokenRequest { + username: string; + password: string; +} +export interface TokenResponse { + token: string; + detail: string; +} +export interface RepositoryRequest { + namespace: string; + name: string; +} +export interface RepositoryResponse { + user: string; + name: string; + namespace: string; + repository_type: string; + status: number; + status_description: string; + description: string; + is_private: boolean; + is_automated: boolean; + can_edit: boolean; + star_count: number; + pull_count: number; + last_updated: string; + date_registered: string; + collaborator_count: number; + affiliation: string; + hub_user: string; + has_starred: boolean; + full_description: string; + permissions: { + read: boolean; + write: boolean; + admin: boolean; + }; + media_types: Array; + content_types: Array; +} +export interface RepositoryTagsRequest { + namespace: string; + name: string; + page?: number; + page_size?: number; +} +export interface RepositoryTagsResponse { + count: number; + next?: string; + previous?: string; + results: Array; +} +export interface RepositoryTagsResult { + creator: number; + id: number; + images: Array; + last_updated: Date; + last_updater: number; + last_updater_username: string; + name: string; + repository: number; + full_size: number; + v2: boolean; + tag_status: string; + tag_last_pulled: Date; + tag_last_pushed: Date; + media_type: string; + content_type: string; + digest: string; +} +export interface RepositoryTagsResultImage { + architecture: string; + features: string; + variant?: string; + digest: string; + os: string; + os_features: string; + os_version?: string; + size: number; + status: string; + last_pulled: Date; + last_pushed: Date; +} +export interface UpdateRepoDescriptionRequest { + name: string; + namespace: string; + description?: string; + full_description: string; +} diff --git a/lib/types/dockerhub.js b/lib/types/dockerhub.js new file mode 100644 index 00000000..21306aba --- /dev/null +++ b/lib/types/dockerhub.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=dockerhub.js.map \ No newline at end of file diff --git a/lib/types/dockerhub.js.map b/lib/types/dockerhub.js.map new file mode 100644 index 00000000..72d8e614 --- /dev/null +++ b/lib/types/dockerhub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dockerhub.js","sourceRoot":"","sources":["../../src/types/dockerhub.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/git.d.ts b/lib/types/git.d.ts new file mode 100644 index 00000000..df0b8794 --- /dev/null +++ b/lib/types/git.d.ts @@ -0,0 +1,17 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Context as GitHubContext } from '@actions/github/lib/context'; +export type Context = GitHubContext; diff --git a/lib/types/git.js b/lib/types/git.js new file mode 100644 index 00000000..ea115f95 --- /dev/null +++ b/lib/types/git.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=git.js.map \ No newline at end of file diff --git a/lib/types/git.js.map b/lib/types/git.js.map new file mode 100644 index 00000000..c0034e2b --- /dev/null +++ b/lib/types/git.js.map @@ -0,0 +1 @@ +{"version":3,"file":"git.js","sourceRoot":"","sources":["../../src/types/git.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/github.d.ts b/lib/types/github.d.ts new file mode 100644 index 00000000..16804845 --- /dev/null +++ b/lib/types/github.d.ts @@ -0,0 +1,50 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { components as OctoOpenApiTypes } from '@octokit/openapi-types'; +import { JwtPayload } from 'jwt-decode'; +import { BakeDefinition } from './buildx/bake'; +import { ExportRecordResponse } from './buildx/history'; +export interface GitHubRelease { + id: number; + tag_name: string; + html_url: string; + assets: Array; +} +export type GitHubRepo = OctoOpenApiTypes['schemas']['repository']; +export interface GitHubActionsRuntimeToken extends JwtPayload { + ac?: string; +} +export interface GitHubActionsRuntimeTokenAC { + Scope: string; + Permission: number; +} +export interface UploadArtifactOpts { + filename: string; + mimeType?: string; + retentionDays?: number; +} +export interface UploadArtifactResponse { + id: number; + filename: string; + size: number; + url: string; +} +export interface BuildSummaryOpts { + exportRes: ExportRecordResponse; + uploadRes: UploadArtifactResponse; + inputs?: any; + bakeDefinition?: BakeDefinition; +} diff --git a/lib/types/github.js b/lib/types/github.js new file mode 100644 index 00000000..54597cf8 --- /dev/null +++ b/lib/types/github.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=github.js.map \ No newline at end of file diff --git a/lib/types/github.js.map b/lib/types/github.js.map new file mode 100644 index 00000000..2d7f9f99 --- /dev/null +++ b/lib/types/github.js.map @@ -0,0 +1 @@ +{"version":3,"file":"github.js","sourceRoot":"","sources":["../../src/types/github.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/intoto/intoto.d.ts b/lib/types/intoto/intoto.d.ts new file mode 100644 index 00000000..16131026 --- /dev/null +++ b/lib/types/intoto/intoto.d.ts @@ -0,0 +1,17 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const MEDIATYPE_PAYLOAD = "application/vnd.in-toto+json"; +export declare const MEDIATYPE_PREDICATE = "in-toto.io/predicate-type"; diff --git a/lib/types/intoto/intoto.js b/lib/types/intoto/intoto.js new file mode 100644 index 00000000..5b45d51f --- /dev/null +++ b/lib/types/intoto/intoto.js @@ -0,0 +1,22 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MEDIATYPE_PREDICATE = exports.MEDIATYPE_PAYLOAD = void 0; +// https://github.com/in-toto/in-toto-golang/blob/dd6278764ab1dae7301609c7510129888e2fd569/in_toto/envelope.go#L17 +exports.MEDIATYPE_PAYLOAD = 'application/vnd.in-toto+json'; +exports.MEDIATYPE_PREDICATE = 'in-toto.io/predicate-type'; +//# sourceMappingURL=intoto.js.map \ No newline at end of file diff --git a/lib/types/intoto/intoto.js.map b/lib/types/intoto/intoto.js.map new file mode 100644 index 00000000..c15e0397 --- /dev/null +++ b/lib/types/intoto/intoto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"intoto.js","sourceRoot":"","sources":["../../../src/types/intoto/intoto.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,kHAAkH;AACrG,QAAA,iBAAiB,GAAG,8BAA8B,CAAC;AAEnD,QAAA,mBAAmB,GAAG,2BAA2B,CAAC"} \ No newline at end of file diff --git a/lib/types/intoto/slsa_provenance/v0.2/provenance.d.ts b/lib/types/intoto/slsa_provenance/v0.2/provenance.d.ts new file mode 100644 index 00000000..e5544503 --- /dev/null +++ b/lib/types/intoto/slsa_provenance/v0.2/provenance.d.ts @@ -0,0 +1,55 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const PREDICATE_SLSA_PROVENANCE = "https://slsa.dev/provenance/v0.2"; +export interface ProvenancePredicate { + builder: ProvenanceBuilder; + buildType: string; + invocation?: ProvenanceInvocation; + buildConfig?: any; + metadata: ProvenanceMetadata; + materials?: Material[]; +} +export interface ProvenanceBuilder { + id: string; +} +export interface ProvenanceInvocation { + configSource?: ConfigSource; + parameters?: any; + environment?: any; +} +export interface DigestSet { + [key: string]: string; +} +export interface ConfigSource { + uri?: string; + digest?: DigestSet; + entryPoint?: string; +} +export interface Completeness { + parameters?: boolean; + environment?: boolean; + materials?: boolean; +} +export interface ProvenanceMetadata { + buildInvocationId?: string; + buildStartedOn?: string; + completeness?: Completeness; + reproducible?: boolean; +} +export interface Material { + uri: string; + digest: DigestSet; +} diff --git a/lib/types/intoto/slsa_provenance/v0.2/provenance.js b/lib/types/intoto/slsa_provenance/v0.2/provenance.js new file mode 100644 index 00000000..4d6de10c --- /dev/null +++ b/lib/types/intoto/slsa_provenance/v0.2/provenance.js @@ -0,0 +1,21 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PREDICATE_SLSA_PROVENANCE = void 0; +// https://github.com/in-toto/in-toto-golang/blob/master/in_toto/slsa_provenance/v0.2/provenance.go +exports.PREDICATE_SLSA_PROVENANCE = 'https://slsa.dev/provenance/v0.2'; +//# sourceMappingURL=provenance.js.map \ No newline at end of file diff --git a/lib/types/intoto/slsa_provenance/v0.2/provenance.js.map b/lib/types/intoto/slsa_provenance/v0.2/provenance.js.map new file mode 100644 index 00000000..81edf40c --- /dev/null +++ b/lib/types/intoto/slsa_provenance/v0.2/provenance.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provenance.js","sourceRoot":"","sources":["../../../../../src/types/intoto/slsa_provenance/v0.2/provenance.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,mGAAmG;AAEtF,QAAA,yBAAyB,GAAG,kCAAkC,CAAC"} \ No newline at end of file diff --git a/lib/types/oci/config.d.ts b/lib/types/oci/config.d.ts new file mode 100644 index 00000000..50189bcb --- /dev/null +++ b/lib/types/oci/config.d.ts @@ -0,0 +1,47 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Digest } from './digest'; +import { Platform } from './descriptor'; +export interface ImageConfig { + User?: string; + ExposedPorts?: Record; + Env?: string[]; + Entrypoint?: string[]; + Cmd?: string[]; + Volumes?: Record; + WorkingDir?: string; + Labels?: Record; + StopSignal?: string; + ArgsEscaped?: boolean; +} +export interface RootFS { + type: string; + diff_ids: Digest[]; +} +export interface History { + created?: string; + created_by?: string; + author?: string; + comment?: string; + empty_layer?: boolean; +} +export interface Image extends Platform { + created?: string; + author?: string; + config?: ImageConfig; + rootfs: RootFS; + history?: History[]; +} diff --git a/lib/types/oci/config.js b/lib/types/oci/config.js new file mode 100644 index 00000000..e575d9ba --- /dev/null +++ b/lib/types/oci/config.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/lib/types/oci/config.js.map b/lib/types/oci/config.js.map new file mode 100644 index 00000000..c6026477 --- /dev/null +++ b/lib/types/oci/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/types/oci/config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/oci/descriptor.d.ts b/lib/types/oci/descriptor.d.ts new file mode 100644 index 00000000..e2680f93 --- /dev/null +++ b/lib/types/oci/descriptor.d.ts @@ -0,0 +1,34 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Digest } from './digest'; +export interface Descriptor { + mediaType: string; + digest: Digest; + size: number; + urls?: string[]; + annotations?: Record; + data?: string; + platform?: Platform; + artifactType?: string; +} +export interface Platform { + architecture: string; + os: string; + 'os.version'?: string; + 'os.features'?: string[]; + variant?: string; +} +export declare const DescriptorEmptyJSON: Descriptor; diff --git a/lib/types/oci/descriptor.js b/lib/types/oci/descriptor.js new file mode 100644 index 00000000..fd763343 --- /dev/null +++ b/lib/types/oci/descriptor.js @@ -0,0 +1,26 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DescriptorEmptyJSON = void 0; +const mediatype_1 = require("./mediatype"); +exports.DescriptorEmptyJSON = { + mediaType: mediatype_1.MEDIATYPE_EMPTY_JSON_V1, + digest: 'sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a', + size: 2, + data: '{}' +}; +//# sourceMappingURL=descriptor.js.map \ No newline at end of file diff --git a/lib/types/oci/descriptor.js.map b/lib/types/oci/descriptor.js.map new file mode 100644 index 00000000..91d3aab0 --- /dev/null +++ b/lib/types/oci/descriptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"descriptor.js","sourceRoot":"","sources":["../../../src/types/oci/descriptor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,2CAAoD;AAqBvC,QAAA,mBAAmB,GAAe;IAC7C,SAAS,EAAE,mCAAuB;IAClC,MAAM,EAAE,yEAAyE;IACjF,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,IAAI;CACX,CAAC"} \ No newline at end of file diff --git a/lib/types/oci/digest.d.ts b/lib/types/oci/digest.d.ts new file mode 100644 index 00000000..57561a26 --- /dev/null +++ b/lib/types/oci/digest.d.ts @@ -0,0 +1,16 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type Digest = string; diff --git a/lib/types/oci/digest.js b/lib/types/oci/digest.js new file mode 100644 index 00000000..cc52ec17 --- /dev/null +++ b/lib/types/oci/digest.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=digest.js.map \ No newline at end of file diff --git a/lib/types/oci/digest.js.map b/lib/types/oci/digest.js.map new file mode 100644 index 00000000..227eaedb --- /dev/null +++ b/lib/types/oci/digest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"digest.js","sourceRoot":"","sources":["../../../src/types/oci/digest.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/oci/index.d.ts b/lib/types/oci/index.d.ts new file mode 100644 index 00000000..a8b887e7 --- /dev/null +++ b/lib/types/oci/index.d.ts @@ -0,0 +1,24 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Versioned } from './versioned'; +import { Descriptor } from './descriptor'; +export interface Index extends Versioned { + mediaType?: string; + artifactType?: string; + manifests: Descriptor[]; + subject?: Descriptor; + annotations?: Record; +} diff --git a/lib/types/oci/index.js b/lib/types/oci/index.js new file mode 100644 index 00000000..43722598 --- /dev/null +++ b/lib/types/oci/index.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/types/oci/index.js.map b/lib/types/oci/index.js.map new file mode 100644 index 00000000..50568cd5 --- /dev/null +++ b/lib/types/oci/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/oci/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/oci/layout.d.ts b/lib/types/oci/layout.d.ts new file mode 100644 index 00000000..409828e7 --- /dev/null +++ b/lib/types/oci/layout.d.ts @@ -0,0 +1,22 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const IMAGE_LAYOUT_FILE_V1 = "oci-layout"; +export declare const IMAGE_LAYOUT_VERSION_V1 = "1.0.0"; +export declare const IMAGE_INDEX_FILE_V1 = "index.json"; +export declare const IMAGE_BLOBS_DIR_V1 = "blobs"; +export interface ImageLayout { + version: string; +} diff --git a/lib/types/oci/layout.js b/lib/types/oci/layout.js new file mode 100644 index 00000000..91bc51c4 --- /dev/null +++ b/lib/types/oci/layout.js @@ -0,0 +1,23 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IMAGE_BLOBS_DIR_V1 = exports.IMAGE_INDEX_FILE_V1 = exports.IMAGE_LAYOUT_VERSION_V1 = exports.IMAGE_LAYOUT_FILE_V1 = void 0; +exports.IMAGE_LAYOUT_FILE_V1 = 'oci-layout'; +exports.IMAGE_LAYOUT_VERSION_V1 = '1.0.0'; +exports.IMAGE_INDEX_FILE_V1 = 'index.json'; +exports.IMAGE_BLOBS_DIR_V1 = 'blobs'; +//# sourceMappingURL=layout.js.map \ No newline at end of file diff --git a/lib/types/oci/layout.js.map b/lib/types/oci/layout.js.map new file mode 100644 index 00000000..05940ef9 --- /dev/null +++ b/lib/types/oci/layout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"layout.js","sourceRoot":"","sources":["../../../src/types/oci/layout.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEU,QAAA,oBAAoB,GAAG,YAAY,CAAC;AAEpC,QAAA,uBAAuB,GAAG,OAAO,CAAC;AAElC,QAAA,mBAAmB,GAAG,YAAY,CAAC;AAEnC,QAAA,kBAAkB,GAAG,OAAO,CAAC"} \ No newline at end of file diff --git a/lib/types/oci/manifest.d.ts b/lib/types/oci/manifest.d.ts new file mode 100644 index 00000000..b948c865 --- /dev/null +++ b/lib/types/oci/manifest.d.ts @@ -0,0 +1,25 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Descriptor } from './descriptor'; +import { Versioned } from './versioned'; +export interface Manifest extends Versioned { + mediaType?: string; + artifactType?: string; + config: Descriptor; + layers: Descriptor[]; + subject?: Descriptor; + annotations?: Record; +} diff --git a/lib/types/oci/manifest.js b/lib/types/oci/manifest.js new file mode 100644 index 00000000..df01dad4 --- /dev/null +++ b/lib/types/oci/manifest.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=manifest.js.map \ No newline at end of file diff --git a/lib/types/oci/manifest.js.map b/lib/types/oci/manifest.js.map new file mode 100644 index 00000000..5d47be5c --- /dev/null +++ b/lib/types/oci/manifest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../../src/types/oci/manifest.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/oci/mediatype.d.ts b/lib/types/oci/mediatype.d.ts new file mode 100644 index 00000000..0b37034a --- /dev/null +++ b/lib/types/oci/mediatype.d.ts @@ -0,0 +1,20 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const MEDIATYPE_DESCRIPTOR_V1 = "application/vnd.oci.descriptor.v1+json"; +export declare const MEDIATYPE_IMAGE_MANIFEST_V1 = "application/vnd.oci.image.manifest.v1+json"; +export declare const MEDIATYPE_IMAGE_INDEX_V1 = "application/vnd.oci.image.index.v1+json"; +export declare const MEDIATYPE_IMAGE_LAYER_V1 = "application/vnd.oci.image.layer.v1.tar"; +export declare const MEDIATYPE_EMPTY_JSON_V1 = "application/vnd.oci.empty.v1+json"; diff --git a/lib/types/oci/mediatype.js b/lib/types/oci/mediatype.js new file mode 100644 index 00000000..a6e7c8d6 --- /dev/null +++ b/lib/types/oci/mediatype.js @@ -0,0 +1,24 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MEDIATYPE_EMPTY_JSON_V1 = exports.MEDIATYPE_IMAGE_LAYER_V1 = exports.MEDIATYPE_IMAGE_INDEX_V1 = exports.MEDIATYPE_IMAGE_MANIFEST_V1 = exports.MEDIATYPE_DESCRIPTOR_V1 = void 0; +exports.MEDIATYPE_DESCRIPTOR_V1 = 'application/vnd.oci.descriptor.v1+json'; +exports.MEDIATYPE_IMAGE_MANIFEST_V1 = 'application/vnd.oci.image.manifest.v1+json'; +exports.MEDIATYPE_IMAGE_INDEX_V1 = 'application/vnd.oci.image.index.v1+json'; +exports.MEDIATYPE_IMAGE_LAYER_V1 = 'application/vnd.oci.image.layer.v1.tar'; +exports.MEDIATYPE_EMPTY_JSON_V1 = 'application/vnd.oci.empty.v1+json'; +//# sourceMappingURL=mediatype.js.map \ No newline at end of file diff --git a/lib/types/oci/mediatype.js.map b/lib/types/oci/mediatype.js.map new file mode 100644 index 00000000..3642567e --- /dev/null +++ b/lib/types/oci/mediatype.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mediatype.js","sourceRoot":"","sources":["../../../src/types/oci/mediatype.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEU,QAAA,uBAAuB,GAAG,wCAAwC,CAAC;AAEnE,QAAA,2BAA2B,GAAG,4CAA4C,CAAC;AAE3E,QAAA,wBAAwB,GAAG,yCAAyC,CAAC;AAErE,QAAA,wBAAwB,GAAG,wCAAwC,CAAC;AAEpE,QAAA,uBAAuB,GAAG,mCAAmC,CAAC"} \ No newline at end of file diff --git a/lib/types/oci/oci.d.ts b/lib/types/oci/oci.d.ts new file mode 100644 index 00000000..0dbc2a37 --- /dev/null +++ b/lib/types/oci/oci.d.ts @@ -0,0 +1,32 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Index } from './index'; +import { ImageLayout } from './layout'; +import { Manifest } from './manifest'; +import { Image } from './config'; +export interface LoadArchiveOpts { + file: string; +} +export interface Archive { + root: { + index: Index; + layout: ImageLayout; + }; + indexes: Record; + manifests: Record; + images: Record; + blobs: Record; +} diff --git a/lib/types/oci/oci.js b/lib/types/oci/oci.js new file mode 100644 index 00000000..aa8c08da --- /dev/null +++ b/lib/types/oci/oci.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=oci.js.map \ No newline at end of file diff --git a/lib/types/oci/oci.js.map b/lib/types/oci/oci.js.map new file mode 100644 index 00000000..eb6be356 --- /dev/null +++ b/lib/types/oci/oci.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oci.js","sourceRoot":"","sources":["../../../src/types/oci/oci.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/types/oci/versioned.d.ts b/lib/types/oci/versioned.d.ts new file mode 100644 index 00000000..78055824 --- /dev/null +++ b/lib/types/oci/versioned.d.ts @@ -0,0 +1,18 @@ +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Versioned { + schemaVersion: number; +} diff --git a/lib/types/oci/versioned.js b/lib/types/oci/versioned.js new file mode 100644 index 00000000..fac28077 --- /dev/null +++ b/lib/types/oci/versioned.js @@ -0,0 +1,18 @@ +"use strict"; +/** + * Copyright 2024 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=versioned.js.map \ No newline at end of file diff --git a/lib/types/oci/versioned.js.map b/lib/types/oci/versioned.js.map new file mode 100644 index 00000000..2808450d --- /dev/null +++ b/lib/types/oci/versioned.js.map @@ -0,0 +1 @@ +{"version":3,"file":"versioned.js","sourceRoot":"","sources":["../../../src/types/oci/versioned.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"} \ No newline at end of file diff --git a/lib/util.d.ts b/lib/util.d.ts new file mode 100644 index 00000000..03a6355d --- /dev/null +++ b/lib/util.d.ts @@ -0,0 +1,41 @@ +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/// +export interface ListOpts { + ignoreComma?: boolean; + comment?: string; + quote?: string | boolean | Buffer | null; +} +export declare class Util { + static getInputList(name: string, opts?: ListOpts): string[]; + static getList(input: string, opts?: ListOpts): string[]; + static asyncForEach(array: any, callback: any): Promise; + static isValidURL(urlStr: string): boolean; + static isValidRef(refStr: string): boolean; + static powershellCommand(script: string, params?: Record): Promise<{ + command: string; + args: string[]; + }>; + static isDirectory(p: any): boolean; + static trimPrefix(str: string, suffix: string): string; + static trimSuffix(str: string, suffix: string): string; + static sleep(seconds: number): Promise; + static hash(input: string): string; + static parseBool(str: string): boolean; + static formatFileSize(bytes: number): string; + static generateRandomString(length?: number): string; + static stringToUnicodeEntities(str: string): string; +} diff --git a/lib/util.js b/lib/util.js new file mode 100644 index 00000000..cc875310 --- /dev/null +++ b/lib/util.js @@ -0,0 +1,213 @@ +"use strict"; +/** + * Copyright 2023 actions-toolkit authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (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.prototype.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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Util = void 0; +const crypto_1 = __importDefault(require("crypto")); +const fs_1 = __importDefault(require("fs")); +const core = __importStar(require("@actions/core")); +const io = __importStar(require("@actions/io")); +const sync_1 = require("csv-parse/sync"); +class Util { + static getInputList(name, opts) { + return this.getList(core.getInput(name), opts); + } + static getList(input, opts) { + const res = []; + if (input == '') { + return res; + } + const records = (0, sync_1.parse)(input, { + columns: false, + relaxQuotes: true, + comment: opts === null || opts === void 0 ? void 0 : opts.comment, + relaxColumnCount: true, + skipEmptyLines: true, + quote: opts === null || opts === void 0 ? void 0 : opts.quote + }); + for (const record of records) { + if (record.length == 1) { + if (opts === null || opts === void 0 ? void 0 : opts.ignoreComma) { + res.push(record[0]); + } + else { + res.push(...record[0].split(',')); + } + } + else if (!(opts === null || opts === void 0 ? void 0 : opts.ignoreComma)) { + res.push(...record); + } + else { + res.push(record.join(',')); + } + } + return res.filter(item => item).map(pat => pat.trim()); + } + static asyncForEach(array, callback) { + return __awaiter(this, void 0, void 0, function* () { + for (let index = 0; index < array.length; index++) { + yield callback(array[index], index, array); + } + }); + } + static isValidURL(urlStr) { + let url; + try { + url = new URL(urlStr); + } + catch (e) { + return false; + } + return url.protocol === 'http:' || url.protocol === 'https:'; + } + static isValidRef(refStr) { + if (Util.isValidURL(refStr)) { + return true; + } + for (const prefix of ['git://', 'github.com/', 'git@']) { + if (refStr.startsWith(prefix)) { + return true; + } + } + return false; + } + static powershellCommand(script, params) { + return __awaiter(this, void 0, void 0, function* () { + const powershellPath = yield io.which('powershell', true); + const escapedScript = script.replace(/'/g, "''").replace(/"|\n|\r/g, ''); + const escapedParams = []; + if (params) { + for (const key in params) { + escapedParams.push(`-${key} '${params[key].replace(/'/g, "''").replace(/"|\n|\r/g, '')}'`); + } + } + return { + command: `"${powershellPath}"`, + args: ['-NoLogo', '-Sta', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-Command', `& '${escapedScript}' ${escapedParams.join(' ')}`] + }; + }); + } + static isDirectory(p) { + try { + return fs_1.default.lstatSync(p).isDirectory(); + } + catch (_) { + // noop + } + return false; + } + static trimPrefix(str, suffix) { + if (!str || !suffix) { + return str; + } + const index = str.indexOf(suffix); + if (index !== 0) { + return str; + } + return str.substring(suffix.length); + } + static trimSuffix(str, suffix) { + if (!str || !suffix) { + return str; + } + const index = str.lastIndexOf(suffix); + if (index === -1 || index + suffix.length !== str.length) { + return str; + } + return str.substring(0, index); + } + static sleep(seconds) { + return new Promise(resolve => setTimeout(resolve, seconds * 1000)); + } + static hash(input) { + return crypto_1.default.createHash('sha256').update(input).digest('hex'); + } + // https://github.com/golang/go/blob/f6b93a4c358b28b350dd8fe1780c1f78e520c09c/src/strconv/atob.go#L7-L18 + static parseBool(str) { + switch (str) { + case '1': + case 't': + case 'T': + case 'true': + case 'TRUE': + case 'True': + return true; + case '0': + case 'f': + case 'F': + case 'false': + case 'FALSE': + case 'False': + return false; + default: + throw new Error(`parseBool syntax error: ${str}`); + } + } + static formatFileSize(bytes) { + if (bytes === 0) + return '0 Bytes'; + const k = 1024; + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; + } + static generateRandomString(length = 10) { + const bytes = crypto_1.default.randomBytes(Math.ceil(length / 2)); + return bytes.toString('hex').slice(0, length); + } + static stringToUnicodeEntities(str) { + return Array.from(str) + .map(char => `&#x${char.charCodeAt(0).toString(16)};`) + .join(''); + } +} +exports.Util = Util; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/lib/util.js.map b/lib/util.js.map new file mode 100644 index 00000000..867ec550 --- /dev/null +++ b/lib/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAA4B;AAC5B,4CAAoB;AACpB,oDAAsC;AACtC,gDAAkC;AAClC,yCAAqC;AAQrC,MAAa,IAAI;IACR,MAAM,CAAC,YAAY,CAAC,IAAY,EAAE,IAAe;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ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