Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
This commit is contained in:
CrazyMax 2020-08-18 17:40:31 +02:00
commit 04eaa7c789
No known key found for this signature in database
GPG key ID: 3248E46B6BB8C7F7
21 changed files with 12365 additions and 0 deletions

15
.editorconfig Normal file
View file

@ -0,0 +1,15 @@
# This file is for unifying the coding style for different editors and IDEs.
# More information at http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

2
.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
/dist/** linguist-generated=true
/lib/** linguist-generated=true

156
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,156 @@
name: ci
on:
push:
branches:
- master
- releases/v*
paths-ignore:
- '**.md'
pull_request:
branches:
- master
- releases/v*
paths-ignore:
- '**.md'
jobs:
main:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
buildx-version:
- latest
- v0.2.2
- ""
steps:
-
name: Checkout
uses: actions/checkout@v2.3.1
-
name: Set up Docker Buildx
id: buildx
uses: ./
with:
version: ${{ matrix.buildx-version }}
-
name: Builder instance name
run: echo ${{ steps.buildx.outputs.name }}
-
name: Available platforms
run: echo ${{ steps.buildx.outputs.platforms }}
-
name: Dump context
uses: crazy-max/ghaction-dump-context@v1
multi:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2.3.1
-
name: Set up Docker Buildx 1
id: buildx1
uses: ./
-
name: Builder 1 instance name
run: echo ${{ steps.buildx1.outputs.name }}
-
name: Set up Docker Buildx 2
id: buildx2
uses: ./
-
name: Builder 2 instance name
run: echo ${{ steps.buildx2.outputs.name }}
install:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2.3.1
-
name: Set up Docker Buildx
uses: ./
with:
install: true
-
name: Check cmd
run: |
docker build --help
use:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
use:
- true
- false
steps:
-
name: Checkout
uses: actions/checkout@v2.3.1
-
name: Set up Docker Buildx
uses: ./
with:
use: ${{ matrix.use }}
-
name: List builder instances
run: docker buildx ls
driver:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
driver-opt:
- image=moby/buildkit:latest
- image=moby/buildkit:master
steps:
-
name: Checkout
uses: actions/checkout@v2.3.1
-
name: Set up Docker Buildx
uses: ./
with:
driver: docker-container
driver-opt: ${{ matrix.driver-opt }}
# with-qemu:
# runs-on: ubuntu-latest
# strategy:
# fail-fast: false
# matrix:
# buildx-version:
# - latest
# - v0.2.2
# - ""
# qemu-platforms:
# - all
# - arm64,riscv64,arm
# steps:
# -
# name: Checkout
# uses: actions/checkout@v2.3.1
# -
# name: Set up QEMU
# uses: docker/setup-qemu-action@master
# with:
# platforms: ${{ matrix.qemu-platforms }}
# -
# name: Set up Docker Buildx
# id: buildx
# uses: ./
# with:
# version: ${{ matrix.buildx-version }}
# -
# name: Available platforms
# run: echo ${{ steps.buildx.outputs.platforms }}
# -
# name: Builder instance name
# run: echo ${{ steps.buildx.outputs.name }}

33
.github/workflows/test.yml vendored Normal file
View file

@ -0,0 +1,33 @@
name: test
on:
push:
branches:
- master
- releases/v*
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
jobs:
test:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2.3.1
-
name: Install
run: yarn install
-
name: Test
run: yarn run test
# -
# name: Upload coverage
# uses: codecov/codecov-action@v1.0.7
# if: success()
# with:
# token: ${{ secrets.CODECOV_TOKEN }}
# file: ./coverage/clover.xml

96
.gitignore vendored Normal file
View file

@ -0,0 +1,96 @@
/.dev
node_modules
lib
# Jetbrains
/.idea
/*.iml
# Rest of the file pulled from https://github.com/github/gitignore/blob/master/Node.gitignore
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/

11
.prettierrc.json Normal file
View file

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

191
LICENSE Normal file
View file

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2013-2018 Docker, Inc.
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
https://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.

118
README.md Normal file
View file

@ -0,0 +1,118 @@
## About
GitHub Action to set up Docker [Buildx](https://github.com/docker/buildx).
___
* [Usage](#usage)
* [Quick start](#quick-start)
* [With QEMU](#with-qemu)
* [Customizing](#customizing)
* [inputs](#inputs)
* [outputs](#outputs)
* [environment variables](#environment-variables)
* [Limitation](#limitation)
## Usage
### Quick start
```yaml
name: ci
on:
push:
jobs:
buildx:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2
-
name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v1
with:
version: latest
-
name: Builder instance name
run: echo ${{ steps.buildx.outputs.name }}
-
name: Available platforms
run: echo ${{ steps.buildx.outputs.platforms }}
```
### With QEMU
If you want support for more platforms you can use our [setup-qemu](https://github.com/docker/setup-qemu-action) action:
```yaml
name: ci
on:
pull_request:
branches: master
push:
branches: master
tags:
jobs:
buildx:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2
-
name: Set up QEMU
uses: docker/setup-qemu-action@v1
with:
platforms: all
-
name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v1
with:
version: latest
-
name: Available platforms
run: echo ${{ steps.buildx.outputs.platforms }}
```
## Customizing
### inputs
Following inputs can be used as `step.with` keys
| Name | Type | Default | Description |
|--------------------|---------|-----------------------------------|------------------------------------|
| `version` | String | _the one installed on the runner_ | [Buildx](https://github.com/docker/buildx) version. e.g. `v0.3.0`, `latest` |
| `driver` | String | `docker-container` | Sets the [builder driver](https://github.com/docker/buildx#--driver-driver) to be used. |
| `driver-opt` | String | | Passes additional [driver-specific options](https://github.com/docker/buildx#--driver-opt-options). e.g. `image=moby/buildkit:master` |
| `buildkitd-flags` | String | | [Flags for buildkitd](https://github.com/moby/buildkit/blob/master/docs/buildkitd.toml.md) daemon. |
| `install` | Bool | `false` | Sets up `docker build` command as an alias to `docker buildx` |
| `use` | Bool | `true` | Switch to this builder instance |
### outputs
Following outputs are available
| Name | Type | Description |
|---------------|---------|---------------------------------------|
| `name` | String | Builder instance name |
| `platforms` | String | Available platforms (comma separated) |
### environment variables
The following [official docker environment variables](https://docs.docker.com/engine/reference/commandline/cli/#environment-variables) are supported:
| Name | Type | Default | Description |
|-----------------|---------|-------------|-------------------------------------------------|
| `DOCKER_CONFIG` | String | `~/.docker` | The location of your client configuration files |
## Limitation
This action is only available for Linux [virtual environments](https://help.github.com/en/articles/virtual-environments-for-github-actions#supported-virtual-environments-and-hardware-resources).

37
__tests__/buildx.test.ts Normal file
View file

@ -0,0 +1,37 @@
import fs = require('fs');
import * as buildx from '../src/buildx';
import * as path from 'path';
import * as os from 'os';
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-buildx-'));
describe('buildx', () => {
it('is available', async () => {
expect(await buildx.isAvailable()).toBe(true);
}, 100000);
it('count builders', async () => {
const countBuilders = await buildx.countBuilders();
console.log(`countBuilders: ${countBuilders}`);
expect(countBuilders).toBeGreaterThan(0);
}, 100000);
it('platforms', async () => {
const platforms = await buildx.platforms();
console.log(`platforms: ${platforms}`);
expect(platforms).not.toBeUndefined();
expect(platforms).not.toEqual('');
}, 100000);
it('acquires v0.2.2 version of buildx', async () => {
const buildxBin = await buildx.install('v0.2.2', tmpDir);
console.log(buildxBin);
expect(fs.existsSync(buildxBin)).toBe(true);
}, 100000);
it('acquires latest version of buildx', async () => {
const buildxBin = await buildx.install('latest', tmpDir);
console.log(buildxBin);
expect(fs.existsSync(buildxBin)).toBe(true);
}, 100000);
});

17
__tests__/github.test.ts Normal file
View file

@ -0,0 +1,17 @@
import * as github from '../src/github';
describe('github', () => {
it('returns latest buildx GitHub release', async () => {
const release = await github.getRelease('latest');
console.log(release);
expect(release).not.toBeNull();
expect(release?.tag_name).not.toEqual('');
});
it('returns v0.2.2 buildx GitHub release', async () => {
const release = await github.getRelease('v0.2.2');
console.log(release);
expect(release).not.toBeNull();
expect(release?.tag_name).toEqual('v0.2.2');
});
});

41
action.yml Normal file
View file

@ -0,0 +1,41 @@
# https://help.github.com/en/articles/metadata-syntax-for-github-actions
name: 'Docker Setup Buildx'
description: 'Set up Docker Buildx'
author: 'docker'
branding:
icon: 'anchor'
color: 'blue'
inputs:
version:
description: 'Buildx version. e.g. v0.3.0'
required: false
driver:
description: 'Sets the builder driver to be used'
default: 'docker-container'
required: false
driver-opt:
description: 'Passes additional driver-specific options. Eg. image=moby/buildkit:master'
required: false
buildkitd-flags:
description: 'Flags for buildkitd daemon'
required: false
install:
description: 'Sets up docker build command as an alias to docker buildx'
default: 'false'
required: false
use:
description: 'Switch to this builder instance'
default: 'true'
required: false
outputs:
name:
description: 'Builder instance name'
platforms:
description: 'Available platforms (comma separated)'
runs:
using: 'node12'
main: 'dist/index.js'
post: 'dist/index.js'

7552
dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

12
jest.config.js Normal file
View file

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

49
package.json Normal file
View file

@ -0,0 +1,49 @@
{
"name": "docker-setup-buildx",
"description": "Set up Docker Buildx",
"main": "lib/main.js",
"scripts": {
"build": "tsc && ncc build",
"format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts",
"test": "jest --coverage",
"pre-checkin": "yarn run format && yarn run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/docker/setup-buildx-action.git"
},
"keywords": [
"actions",
"docker",
"buildx"
],
"author": "Docker",
"contributors": [
{
"name": "CrazyMax",
"url": "https://crazymax.dev"
}
],
"license": "Apache-2.0",
"dependencies": {
"@actions/core": "^1.2.4",
"@actions/exec": "^1.0.4",
"@actions/http-client": "^1.0.8",
"@actions/tool-cache": "^1.5.5",
"semver": "^7.3.2"
},
"devDependencies": {
"@types/jest": "^26.0.3",
"@types/node": "^14.0.14",
"@zeit/ncc": "^0.22.3",
"dotenv": "^8.2.0",
"jest": "^26.1.0",
"jest-circus": "^26.1.0",
"jest-runtime": "^26.1.0",
"prettier": "^2.0.5",
"ts-jest": "^26.1.1",
"typescript": "^3.9.5",
"typescript-formatter": "^7.2.2"
}
}

98
src/buildx.ts Normal file
View file

@ -0,0 +1,98 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as semver from 'semver';
import * as util from 'util';
import * as exec from './exec';
import * as github from './github';
import * as core from '@actions/core';
import * as tc from '@actions/tool-cache';
const osPlat: string = os.platform();
export async function isAvailable(): Promise<Boolean> {
return await exec.exec(`docker`, ['buildx'], true).then(res => {
if (res.stderr != '' && !res.success) {
return false;
}
return res.success;
});
}
export async function countBuilders(): Promise<number> {
return await exec.exec(`docker`, ['buildx', 'ls'], true).then(res => {
if (res.stderr != '' && !res.success) {
throw new Error(`Cannot list builders: ${res.stderr}`);
}
return (res.stdout.trim().split(`\n`).length - 1) / 2;
});
}
export async function platforms(): Promise<String | undefined> {
return await exec.exec(`docker`, ['buildx', 'inspect'], true).then(res => {
if (res.stderr != '' && !res.success) {
throw new Error(res.stderr);
}
for (const line of res.stdout.trim().split(`\n`)) {
if (line.startsWith('Platforms')) {
return line.replace('Platforms: ', '').replace(/\s/g, '').trim();
}
}
});
}
export async function install(inputVersion: string, dockerConfigHome: string): Promise<string> {
const release: github.GitHubRelease | null = await github.getRelease(inputVersion);
if (!release) {
throw new Error(`Cannot find buildx ${inputVersion} release`);
}
core.debug(`Release found: ${release.tag_name}`);
const version = release.tag_name.replace(/^v+|v+$/g, '');
let toolPath: string;
toolPath = tc.find('buildx', version);
if (!toolPath) {
const c = semver.clean(version) || '';
if (!semver.valid(c)) {
throw new Error(`Invalid Buildx version "${version}".`);
}
toolPath = await download(version);
}
const pluginsDir: string = path.join(dockerConfigHome, 'cli-plugins');
core.debug(`Plugins dir is ${pluginsDir}`);
if (!fs.existsSync(pluginsDir)) {
fs.mkdirSync(pluginsDir, {recursive: true});
}
const filename: string = osPlat == 'win32' ? 'docker-buildx.exe' : 'docker-buildx';
const pluginPath: string = path.join(pluginsDir, filename);
core.debug(`Plugin path is ${pluginPath}`);
fs.copyFileSync(path.join(toolPath, filename), pluginPath);
core.info('🔨 Fixing perms...');
fs.chmodSync(pluginPath, '0755');
return pluginPath;
}
async function download(version: string): Promise<string> {
version = semver.clean(version) || '';
const platform: string = osPlat == 'win32' ? 'windows' : osPlat;
const ext: string = osPlat == 'win32' ? '.exe' : '';
const filename: string = util.format('buildx-v%s.%s-amd64%s', version, platform, ext);
const targetFile: string = osPlat == 'win32' ? 'docker-buildx.exe' : 'docker-buildx';
const downloadUrl = util.format('https://github.com/docker/buildx/releases/download/v%s/%s', version, filename);
let downloadPath: string;
try {
core.info(`⬇️ Downloading ${downloadUrl}...`);
downloadPath = await tc.downloadTool(downloadUrl);
core.debug(`Downloaded to ${downloadPath}`);
} catch (error) {
throw error;
}
return await tc.cacheFile(downloadPath, targetFile, 'buildx', version);
}

34
src/exec.ts Normal file
View file

@ -0,0 +1,34 @@
import * as aexec from '@actions/exec';
import {ExecOptions} from '@actions/exec';
export interface ExecResult {
success: boolean;
stdout: string;
stderr: string;
}
export const exec = async (command: string, args: string[] = [], silent: boolean): Promise<ExecResult> => {
let stdout: string = '';
let stderr: string = '';
const options: ExecOptions = {
silent: silent,
ignoreReturnCode: true
};
options.listeners = {
stdout: (data: Buffer) => {
stdout += data.toString();
},
stderr: (data: Buffer) => {
stderr += data.toString();
}
};
const returnCode: number = await aexec.exec(command, args, options);
return {
success: returnCode === 0,
stdout: stdout.trim(),
stderr: stderr.trim()
};
};

12
src/github.ts Normal file
View file

@ -0,0 +1,12 @@
import * as httpm from '@actions/http-client';
export interface GitHubRelease {
id: number;
tag_name: string;
}
export const getRelease = async (version: string): Promise<GitHubRelease | null> => {
const url: string = `https://github.com/docker/buildx/releases/${version}`;
const http: httpm.HttpClient = new httpm.HttpClient('setup-buildx');
return (await http.getJson<GitHubRelease>(url)).result;
};

82
src/main.ts Normal file
View file

@ -0,0 +1,82 @@
import * as os from 'os';
import * as path from 'path';
import * as buildx from './buildx';
import * as mexec from './exec';
import * as stateHelper from './state-helper';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
async function run(): Promise<void> {
try {
if (os.platform() !== 'linux') {
core.setFailed('Only supported on linux platform');
return;
}
const bxVersion: string = core.getInput('version');
const bxDriver: string = core.getInput('driver') || 'docker-container';
const bxDriverOpt: string = core.getInput('driver-opt');
const bxBuildkitdFlags: string = core.getInput('buildkitd-flags');
const bxInstall: boolean = /true/i.test(core.getInput('install'));
const bxUse: boolean = /true/i.test(core.getInput('use'));
const dockerConfigHome: string = process.env.DOCKER_CONFIG || path.join(os.homedir(), '.docker');
if (!(await buildx.isAvailable()) || bxVersion) {
await buildx.install(bxVersion || 'latest', dockerConfigHome);
}
core.info('📣 Buildx info');
await exec.exec('docker', ['buildx', 'version']);
const builderName: string = `builder-${process.env.GITHUB_JOB}-${(await buildx.countBuilders()) + 1}`;
core.setOutput('name', builderName);
stateHelper.setBuilderName(builderName);
core.info('🔨 Creating a new builder instance...');
let createArgs: Array<string> = ['buildx', 'create', '--name', builderName, '--driver', bxDriver];
if (bxDriverOpt) {
createArgs.push('--driver-opt', bxDriverOpt);
}
if (bxBuildkitdFlags) {
createArgs.push('--buildkitd-flags', bxBuildkitdFlags);
}
if (bxUse) {
createArgs.push('--use');
}
await exec.exec('docker', createArgs);
core.info('🏃 Booting builder...');
await exec.exec('docker', ['buildx', 'inspect', '--bootstrap']);
if (bxInstall) {
core.info('🤝 Setting buildx as default builder...');
await exec.exec('docker', ['buildx', 'install']);
}
core.info('🛒 Extracting available platforms...');
const platforms = await buildx.platforms();
core.info(`${platforms}`);
core.setOutput('platforms', platforms);
} catch (error) {
core.setFailed(error.message);
}
}
async function cleanup(): Promise<void> {
if (stateHelper.builderName.length == 0) {
return;
}
await mexec.exec('docker', ['buildx', 'rm', `${stateHelper.builderName}`], false).then(res => {
if (res.stderr != '' && !res.success) {
core.warning(res.stderr);
}
});
}
if (!stateHelper.IsPost) {
run();
} else {
cleanup();
}

12
src/state-helper.ts Normal file
View file

@ -0,0 +1,12 @@
import * as core from '@actions/core';
export const IsPost = !!process.env['STATE_isPost'];
export const builderName = process.env['STATE_builderName'] || '';
export function setBuilderName(builderName: string) {
core.saveState('builderName', builderName);
}
if (!IsPost) {
core.saveState('isPost', 'true');
}

18
tsconfig.json Normal file
View file

@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"newLine": "lf",
"outDir": "./lib",
"rootDir": "./src",
"strict": true,
"noImplicitAny": false,
"esModuleInterop": true,
"sourceMap": true
},
"exclude": ["node_modules", "**/*.test.ts"]
}

3779
yarn.lock Normal file

File diff suppressed because it is too large Load diff