Compare commits

..

40 Commits

Author SHA1 Message Date
CrazyMax
580aee99c0 Merge pull request #46 from crazy-max/buildx-split-install
Some checks failed
publish / publish (push) Has been cancelled
buildx: split install from download and build methods
2023-02-19 03:39:55 +01:00
CrazyMax
89ecd37681 buildx: info logs on install
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-19 03:34:30 +01:00
CrazyMax
139fb39ab0 buildx: split install from download and build methods
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-19 03:25:07 +01:00
CrazyMax
67957d8c7a Merge pull request #45 from crazy-max/docker-fix
docker: various fixes
2023-02-19 02:57:48 +01:00
CrazyMax
768df5fbf4 buildx: debug logs in isAvailable method
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-19 02:54:07 +01:00
CrazyMax
e9db81b6a1 docker: fix printVersion and printInfo
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-19 02:54:06 +01:00
CrazyMax
cd825ae548 docker: remove singleton
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-19 02:54:06 +01:00
CrazyMax
28c11a1819 Merge pull request #44 from crazy-max/cleanup
chore: remove path sep conversion
2023-02-19 01:52:35 +01:00
CrazyMax
ed087e5b0d chore: remove path sep conversion
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-19 00:59:04 +01:00
CrazyMax
2038d87306 Merge pull request #43 from crazy-max/fix-standalone
Some checks failed
publish / publish (push) Has been cancelled
fix buildx standalone and check for docker availability
2023-02-18 10:15:26 +01:00
CrazyMax
252c717cc3 fix buildx standalone and check for docker availability
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 10:09:41 +01:00
CrazyMax
9b338b58a7 toolkit: docker property not needed
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 10:08:21 +01:00
CrazyMax
abe37ab72b Merge pull request #42 from crazy-max/buildkit-fix-version
Some checks failed
publish / publish (push) Has been cancelled
buildkit: use node info to retrieve version
2023-02-18 07:34:55 +01:00
CrazyMax
b3a30a9e32 Merge pull request #41 from crazy-max/fix-docker
docker: fix instance
2023-02-18 07:32:33 +01:00
CrazyMax
31e915c017 buildkit: use node info to retrieve version
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 07:31:21 +01:00
CrazyMax
05bbe49fe1 toolkit: add docker
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 07:06:29 +01:00
CrazyMax
c80fedbbae docker: fix instance
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 07:06:20 +01:00
CrazyMax
2c60cad840 Merge pull request #40 from crazy-max/debug
Some checks failed
publish / publish (push) Has been cancelled
some debug logs
2023-02-18 06:00:54 +01:00
CrazyMax
847887b312 some debug logs
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 04:36:32 +01:00
CrazyMax
d9984214c9 Merge pull request #39 from crazy-max/buildkit-ctn-prefix
buildx: make containerNamePrefix static and public
2023-02-18 02:20:37 +01:00
CrazyMax
33b4390bc2 buildx: make containerNamePrefix static and public
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 02:12:09 +01:00
CrazyMax
5e8f679709 Merge pull request #38 from crazy-max/util-quote
Some checks failed
publish / publish (push) Has been cancelled
util: handle quote opt with the same api for input list
2023-02-18 01:57:40 +01:00
CrazyMax
f288f4f7ea util: handle quote opt with the same api for input list
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 01:53:59 +01:00
CrazyMax
cb9121174a Merge pull request #37 from crazy-max/toolkit-builder
toolkit: add builder
2023-02-18 01:37:42 +01:00
CrazyMax
464dfbe1ec toolkit: add builder
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 01:33:37 +01:00
CrazyMax
5695c0049b Merge pull request #36 from crazy-max/update-input-list
Some checks failed
publish / publish (push) Has been cancelled
util: opt to escape quotes for input list
2023-02-18 01:12:26 +01:00
CrazyMax
44b1545abd util: opt to escape quotes for input list
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-18 01:02:56 +01:00
CrazyMax
4d9d62d542 Merge pull request #35 from crazy-max/node-type
builder: add Node type
2023-02-18 00:01:23 +01:00
CrazyMax
aa3c8ef106 Merge pull request #34 from crazy-max/buildx-optional-dest
buildx: dest dir optional on install
2023-02-17 23:58:35 +01:00
CrazyMax
259abb56df builder: add Node type
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-17 23:56:13 +01:00
CrazyMax
76e5a25cff buildx: dest dir optional on install
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-17 23:54:28 +01:00
CrazyMax
bb8a659d9e Merge pull request #33 from crazy-max/package-json-ver
Some checks failed
publish / publish (push) Has been cancelled
set dev version in package json
2023-02-17 22:34:10 +01:00
CrazyMax
6ab0483b34 set dev version in package json
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-17 22:31:14 +01:00
CrazyMax
d7dbf54456 Merge pull request #32 from crazy-max/buildx-build
buildx: build buildx as install method
2023-02-17 22:04:44 +01:00
CrazyMax
496d7e2c9d toolkit: add buildxInstall
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-17 21:56:55 +01:00
CrazyMax
094239d9eb buildx: build buildx as install method
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-17 21:56:41 +01:00
CrazyMax
c8a13a2352 buildx: remove install method from main module
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-17 21:52:11 +01:00
CrazyMax
875c6c9e95 Merge pull request #31 from crazy-max/buildx-install
buildx: install method
2023-02-17 20:14:42 +01:00
CrazyMax
12e3bd7469 cleanup temp dir after each test when installing buildx
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-17 20:00:56 +01:00
CrazyMax
2abe456e6b buildx: install method
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2023-02-17 20:00:18 +01:00
20 changed files with 301 additions and 159 deletions

View File

@@ -15,7 +15,6 @@
*/
import {beforeEach, describe, expect, it, jest, test} from '@jest/globals';
import * as semver from 'semver';
import {BuildKit} from '../../src/buildkit/buildkit';
import {Builder} from '../../src/buildx/builder';
@@ -48,11 +47,15 @@ jest.spyOn(Builder.prototype, 'inspect').mockImplementation(async (): Promise<Bu
describe('getVersion', () => {
it('valid', async () => {
const builder = new Builder({
context: new Context()
});
const builderInfo = await builder.inspect('builder2');
const buildkit = new BuildKit({
context: new Context()
});
const version = await buildkit.getVersion('builder2');
expect(semver.valid(version)).not.toBeNull();
const version = await buildkit.getVersion(builderInfo.nodes[0]);
expect(version).toBe('v0.11.0');
});
});

View File

@@ -24,8 +24,8 @@ import {Context} from '../../src/context';
const fixturesDir = path.join(__dirname, '..', 'fixtures');
// prettier-ignore
const tmpDir = path.join(process.env.TEMP || '/tmp', 'buildkit-config-jest').split(path.sep).join(path.posix.sep);
const tmpName = path.join(tmpDir, '.tmpname-jest').split(path.sep).join(path.posix.sep);
const tmpDir = path.join(process.env.TEMP || '/tmp', 'buildkit-config-jest');
const tmpName = path.join(tmpDir, '.tmpname-jest');
jest.spyOn(Context.prototype, 'tmpDir').mockImplementation((): string => {
if (!fs.existsSync(tmpDir)) {
@@ -50,7 +50,7 @@ describe('resolve', () => {
['debug = true', false, 'debug = true', null],
[`notfound.toml`, true, '', new Error('config file notfound.toml not found')],
[
`${path.join(fixturesDir, 'buildkitd.toml').split(path.sep).join(path.posix.sep)}`,
`${path.join(fixturesDir, 'buildkitd.toml')}`,
true,
`debug = true
[registry."docker.io"]

View File

@@ -27,8 +27,8 @@ import {Context} from '../../src/context';
import {Cert} from '../../src/types/buildx';
// prettier-ignore
const tmpDir = path.join(process.env.TEMP || '/tmp', 'buildx-jest').split(path.sep).join(path.posix.sep);
const tmpName = path.join(tmpDir, '.tmpname-jest').split(path.sep).join(path.posix.sep);
const tmpDir = path.join(process.env.TEMP || '/tmp', 'buildx-jest');
const tmpName = path.join(tmpDir, '.tmpname-jest');
jest.spyOn(Context.prototype, 'tmpDir').mockImplementation((): string => {
if (!fs.existsSync(tmpDir)) {
@@ -95,9 +95,7 @@ describe('isAvailable', () => {
context: new Context(),
standalone: false
});
buildx.isAvailable().catch(() => {
// noop
});
await buildx.isAvailable();
// eslint-disable-next-line jest/no-standalone-expect
expect(execSpy).toHaveBeenCalledWith(`docker`, ['buildx'], {
silent: true,
@@ -110,9 +108,7 @@ describe('isAvailable', () => {
context: new Context(),
standalone: true
});
buildx.isAvailable().catch(() => {
// noop
});
await buildx.isAvailable();
// eslint-disable-next-line jest/no-standalone-expect
expect(execSpy).toHaveBeenCalledWith(`buildx`, [], {
silent: true,
@@ -122,13 +118,13 @@ describe('isAvailable', () => {
});
describe('printInspect', () => {
it('prints builder2 instance', () => {
it('prints builder2 instance', async () => {
const execSpy = jest.spyOn(exec, 'exec');
const buildx = new Buildx({
context: new Context(),
standalone: true
});
buildx.printInspect('builder2').catch(() => {
await buildx.printInspect('builder2').catch(() => {
// noop
});
expect(execSpy).toHaveBeenCalledWith(`buildx`, ['inspect', 'builder2'], {
@@ -138,24 +134,24 @@ describe('printInspect', () => {
});
describe('printVersion', () => {
it('docker cli', () => {
it('docker cli', async () => {
const execSpy = jest.spyOn(exec, 'exec');
const buildx = new Buildx({
context: new Context(),
standalone: false
});
buildx.printVersion();
await buildx.printVersion();
expect(execSpy).toHaveBeenCalledWith(`docker`, ['buildx', 'version'], {
failOnStdErr: false
});
});
it('standalone', () => {
it('standalone', async () => {
const execSpy = jest.spyOn(exec, 'exec');
const buildx = new Buildx({
context: new Context(),
standalone: true
});
buildx.printVersion();
await buildx.printVersion();
expect(execSpy).toHaveBeenCalledWith(`buildx`, ['version'], {
failOnStdErr: false
});

View File

@@ -25,8 +25,8 @@ import {Inputs} from '../../src/buildx/inputs';
const fixturesDir = path.join(__dirname, '..', 'fixtures');
// prettier-ignore
const tmpDir = path.join(process.env.TEMP || '/tmp', 'buildx-inputs-jest').split(path.sep).join(path.posix.sep);
const tmpName = path.join(tmpDir, '.tmpname-jest').split(path.sep).join(path.posix.sep);
const tmpDir = path.join(process.env.TEMP || '/tmp', 'buildx-inputs-jest');
const tmpName = path.join(tmpDir, '.tmpname-jest');
const metadata = `{
"containerimage.config.digest": "sha256:059b68a595b22564a1cbc167af369349fdc2ecc1f7bc092c2235cbf601a795fd",
"containerimage.digest": "sha256:b09b9482c72371486bb2c1d2c2a2633ed1d0b8389e12c8d52b9e052725c0c83c"
@@ -175,7 +175,7 @@ describe('resolveBuildSecret', () => {
['aaaaaaaa', false, '', '', new Error('aaaaaaaa is not a valid secret')],
['aaaaaaaa=', false, '', '', new Error('aaaaaaaa= is not a valid secret')],
['=bbbbbbb', false, '', '', new Error('=bbbbbbb is not a valid secret')],
[`foo=${path.join(fixturesDir, 'secret.txt').split(path.sep).join(path.posix.sep)}`, true, 'foo', 'bar', null],
[`foo=${path.join(fixturesDir, 'secret.txt')}`, true, 'foo', 'bar', null],
[`notfound=secret`, true, '', '', new Error('secret file secret not found')]
])('given %p key and %p secret', async (kvp: string, file: boolean, exKey: string, exValue: string, error: Error) => {
try {

View File

@@ -14,31 +14,43 @@
* limitations under the License.
*/
import {describe, expect, it, jest, test, beforeEach} from '@jest/globals';
import {describe, expect, it, jest, test, beforeEach, afterEach} from '@jest/globals';
import * as fs from 'fs';
import * as path from 'path';
import * as rimraf from 'rimraf';
import osm = require('os');
import {Install} from '../../src/buildx/install';
// prettier-ignore
const tmpDir = path.join(process.env.TEMP || '/tmp', 'buildx-jest');
beforeEach(() => {
jest.clearAllMocks();
});
describe('install', () => {
// prettier-ignore
const tmpDir = path.join(process.env.TEMP || '/tmp', 'buildx-install-jest').split(path.sep).join(path.posix.sep);
afterEach(function () {
rimraf.sync(tmpDir);
});
describe('download', () => {
// prettier-ignore
test.each([
['v0.4.1', false],
['v0.9.1', false],
['latest', false],
['v0.4.1', true],
['v0.9.1', true],
['latest', true]
])(
'acquires %p of buildx (standalone: %p)', async (version, standalone) => {
const install = new Install({standalone: standalone});
const buildxBin = await install.install(version, tmpDir);
const toolPath = await install.download(version);
expect(fs.existsSync(toolPath)).toBe(true);
let buildxBin: string;
if (standalone) {
buildxBin = await install.installStandalone(toolPath, tmpDir);
} else {
buildxBin = await install.installPlugin(toolPath, tmpDir);
}
expect(fs.existsSync(buildxBin)).toBe(true);
},
100000
@@ -60,7 +72,7 @@ describe('install', () => {
jest.spyOn(osm, 'platform').mockImplementation(() => os);
jest.spyOn(osm, 'arch').mockImplementation(() => arch);
const install = new Install();
const buildxBin = await install.install('latest', tmpDir);
const buildxBin = await install.download('latest');
expect(fs.existsSync(buildxBin)).toBe(true);
},
100000
@@ -73,6 +85,26 @@ describe('install', () => {
});
});
describe('build', () => {
// eslint-disable-next-line jest/no-disabled-tests
it.skip('builds refs/pull/648/head', async () => {
const install = new Install();
const toolPath = await install.build('https://github.com/docker/buildx.git#refs/pull/648/head');
expect(fs.existsSync(toolPath)).toBe(true);
const buildxBin = await install.installStandalone(toolPath, tmpDir);
expect(fs.existsSync(buildxBin)).toBe(true);
}, 100000);
// eslint-disable-next-line jest/no-disabled-tests
it.skip('builds 67bd6f4dc82a9cd96f34133dab3f6f7af803bb14', async () => {
const install = new Install();
const toolPath = await install.build('https://github.com/docker/buildx.git#67bd6f4dc82a9cd96f34133dab3f6f7af803bb14');
expect(fs.existsSync(toolPath)).toBe(true);
const buildxBin = await install.installPlugin(toolPath, tmpDir);
expect(fs.existsSync(buildxBin)).toBe(true);
}, 100000);
});
describe('getRelease', () => {
it('returns latest buildx GitHub release', async () => {
const release = await Install.getRelease('latest');

View File

@@ -22,8 +22,8 @@ import {describe, expect, jest, it, beforeEach, afterEach} from '@jest/globals';
import {Context} from '../src/context';
// prettier-ignore
const tmpDir = path.join(process.env.TEMP || '/tmp', 'context-jest').split(path.sep).join(path.posix.sep);
const tmpName = path.join(tmpDir, '.tmpname-jest').split(path.sep).join(path.posix.sep);
const tmpDir = path.join(process.env.TEMP || '/tmp', 'context-jest');
const tmpName = path.join(tmpDir, '.tmpname-jest');
jest.spyOn(Context.prototype, 'tmpDir').mockImplementation((): string => {
if (!fs.existsSync(tmpDir)) {

View File

@@ -48,9 +48,9 @@ describe('configDir', () => {
});
describe('isAvailable', () => {
it('cli', () => {
it('cli', async () => {
const execSpy = jest.spyOn(exec, 'getExecOutput');
Docker.isAvailable;
await Docker.isAvailable();
// eslint-disable-next-line jest/no-standalone-expect
expect(execSpy).toHaveBeenCalledWith(`docker`, undefined, {
silent: true,
@@ -60,43 +60,21 @@ describe('isAvailable', () => {
});
describe('printVersion', () => {
it('docker cli', () => {
it('call docker version', async () => {
const execSpy = jest.spyOn(exec, 'exec');
Docker.printVersion(false).catch(() => {
await Docker.printVersion().catch(() => {
// noop
});
expect(execSpy).toHaveBeenCalledWith(`docker`, ['version'], {
failOnStdErr: false
});
});
it('standalone', () => {
const execSpy = jest.spyOn(exec, 'exec');
Docker.printVersion(true).catch(() => {
// noop
});
expect(execSpy).not.toHaveBeenCalledWith(`docker`, ['version'], {
failOnStdErr: false
});
expect(execSpy).toHaveBeenCalledWith(`docker`, ['version']);
});
});
describe('printInfo', () => {
it('docker cli', () => {
it('call docker info', async () => {
const execSpy = jest.spyOn(exec, 'exec');
Docker.printInfo(false).catch(() => {
await Docker.printInfo().catch(() => {
// noop
});
expect(execSpy).toHaveBeenCalledWith(`docker`, ['info'], {
failOnStdErr: false
});
});
it('standalone', () => {
const execSpy = jest.spyOn(exec, 'exec');
Docker.printInfo(true).catch(() => {
// noop
});
expect(execSpy).not.toHaveBeenCalledWith(`docker`, ['info'], {
failOnStdErr: false
});
expect(execSpy).toHaveBeenCalledWith(`docker`, ['info']);
});
});

View File

@@ -69,16 +69,28 @@ describe('getInputList', () => {
it('multiline and ignoring comma correctly', async () => {
setInput('cache-from', 'user/app:cache\ntype=local,src=path/to/dir');
const res = Util.getInputList('cache-from', true);
const res = Util.getInputList('cache-from', {ignoreComma: true});
expect(res).toEqual(['user/app:cache', 'type=local,src=path/to/dir']);
});
it('different new lines and ignoring comma correctly', async () => {
setInput('cache-from', 'user/app:cache\r\ntype=local,src=path/to/dir');
const res = Util.getInputList('cache-from', true);
const res = Util.getInputList('cache-from', {ignoreComma: true});
expect(res).toEqual(['user/app:cache', 'type=local,src=path/to/dir']);
});
it('do not escape surrounding quotes', async () => {
setInput('driver-opts', `"env.no_proxy=localhost,127.0.0.1,.mydomain"`);
const res = Util.getInputList('driver-opts', {ignoreComma: true, quote: false});
expect(res).toEqual(['"env.no_proxy=localhost,127.0.0.1,.mydomain"']);
});
it('escape surrounding quotes', async () => {
setInput('platforms', 'linux/amd64\n"linux/arm64,linux/arm/v7"');
const res = Util.getInputList('platforms');
expect(res).toEqual(['linux/amd64', 'linux/arm64', 'linux/arm/v7']);
});
it('multiline values', async () => {
setInput(
'secrets',
@@ -88,7 +100,7 @@ bbbbbbb
ccccccccc"
FOO=bar`
);
const res = Util.getInputList('secrets', true);
const res = Util.getInputList('secrets', {ignoreComma: true});
expect(res).toEqual([
'GIT_AUTH_TOKEN=abcdefgh,ijklmno=0123456789',
`MYSECRET=aaaaaaaa
@@ -111,7 +123,7 @@ FOO=bar
bbbb
ccc"`
);
const res = Util.getInputList('secrets', true);
const res = Util.getInputList('secrets', {ignoreComma: true});
expect(res).toEqual([
'GIT_AUTH_TOKEN=abcdefgh,ijklmno=0123456789',
`MYSECRET=aaaaaaaa
@@ -134,7 +146,7 @@ bbbbbbb
ccccccccc
FOO=bar`
);
const res = Util.getInputList('secrets', true);
const res = Util.getInputList('secrets', {ignoreComma: true});
expect(res).toEqual(['GIT_AUTH_TOKEN=abcdefgh,ijklmno=0123456789', 'MYSECRET=aaaaaaaa', 'bbbbbbb', 'ccccccccc', 'FOO=bar']);
});
@@ -145,7 +157,7 @@ FOO=bar`
`"GPG_KEY=${pgp}"
FOO=bar`
);
const res = Util.getInputList('secrets', true);
const res = Util.getInputList('secrets', {ignoreComma: true});
expect(res).toEqual([`GPG_KEY=${pgp}`, 'FOO=bar']);
});
@@ -158,7 +170,7 @@ bbbb""bbb
ccccccccc"
FOO=bar`
);
const res = Util.getInputList('secrets', true);
const res = Util.getInputList('secrets', {ignoreComma: true});
expect(res).toEqual([
'GIT_AUTH_TOKEN=abcdefgh,ijklmno=0123456789',
`MYSECRET=aaaaaaaa

View File

@@ -18,13 +18,13 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'docker-actions-toolkit-')).split(path.sep).join(path.posix.sep);
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'docker-actions-toolkit-'));
process.env = Object.assign({}, process.env, {
TEMP: tmpDir,
GITHUB_REPOSITORY: 'docker/actions-toolkit',
RUNNER_TEMP: path.join(tmpDir, 'runner-temp').split(path.sep).join(path.posix.sep),
RUNNER_TOOL_CACHE: path.join(tmpDir, 'runner-tool-cache').split(path.sep).join(path.posix.sep)
RUNNER_TEMP: path.join(tmpDir, 'runner-temp'),
RUNNER_TOOL_CACHE: path.join(tmpDir, 'runner-tool-cache')
}) as {
[key: string]: string;
};

View File

@@ -1,5 +1,6 @@
{
"name": "@docker/actions-toolkit",
"version": "0.0.0+unknown",
"description": "Toolkit for Docker (GitHub) Actions",
"scripts": {
"build": "tsc",

View File

@@ -23,7 +23,7 @@ import {Buildx} from '../buildx/buildx';
import {Builder} from '../buildx/builder';
import {Config} from './config';
import {BuilderInfo} from '../types/builder';
import {BuilderInfo, NodeInfo} from '../types/builder';
export interface BuildKitOpts {
context: Context;
@@ -33,7 +33,6 @@ export interface BuildKitOpts {
export class BuildKit {
private readonly context: Context;
private readonly buildx: Buildx;
private containerNamePrefix = 'buildx_buildkit_';
public readonly config: Config;
@@ -47,14 +46,7 @@ export class BuildKit {
});
}
public async getVersion(builderName: string): Promise<string | undefined> {
const builderInfo = await this.getBuilderInfo(builderName);
if (builderInfo.nodes.length == 0) {
// a builder always have on node, should not happen.
return undefined;
}
// TODO: get version for all nodes
const node = builderInfo.nodes[0];
public async getVersion(node: NodeInfo): Promise<string | undefined> {
if (!node.buildkitVersion && node.name) {
try {
return await this.getVersionWithinImage(node.name);
@@ -66,13 +58,15 @@ export class BuildKit {
}
private async getVersionWithinImage(nodeName: string): Promise<string> {
core.debug(`BuildKit.getVersionWithinImage nodeName: ${nodeName}`);
return exec
.getExecOutput(`docker`, ['inspect', '--format', '{{.Config.Image}}', `${this.containerNamePrefix}${nodeName}`], {
.getExecOutput(`docker`, ['inspect', '--format', '{{.Config.Image}}', `${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
.getExecOutput(`docker`, ['run', '--rm', bkitimage.stdout.trim(), '--version'], {
ignoreReturnCode: true,
@@ -93,17 +87,25 @@ export class BuildKit {
});
}
public async versionSatisfies(builderName: string, range: string): Promise<boolean> {
const builderInfo = await this.getBuilderInfo(builderName);
public async versionSatisfies(builderName: string, range: string, builderInfo?: BuilderInfo): Promise<boolean> {
if (!builderInfo) {
builderInfo = await new Builder({
context: this.context,
buildx: this.buildx
}).inspect(builderName);
}
for (const node of builderInfo.nodes) {
core.debug(`BuildKit.versionSatisfies ${node}: ${range}`);
let bkversion = node.buildkitVersion;
if (!bkversion) {
try {
bkversion = await this.getVersionWithinImage(node.name || '');
} catch (e) {
core.debug(`BuildKit.versionSatisfies ${node}: can't get version`);
return false;
}
}
core.debug(`BuildKit.versionSatisfies ${node}: 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;
@@ -114,12 +116,4 @@ export class BuildKit {
}
return true;
}
private async getBuilderInfo(name: string): Promise<BuilderInfo> {
const builder = new Builder({
context: this.context,
buildx: this.buildx
});
return builder.inspect(name);
}
}

View File

@@ -40,7 +40,7 @@ export class Builder {
}
public async inspect(name: string): Promise<BuilderInfo> {
const cmd = this.buildx.getCommand(['inspect', name]);
const cmd = await this.buildx.getCommand(['inspect', name]);
return await exec
.getExecOutput(cmd.command, cmd.args, {
ignoreReturnCode: true,

View File

@@ -16,13 +16,13 @@
import fs from 'fs';
import path from 'path';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as semver from 'semver';
import {Docker} from '../docker';
import {Context} from '../context';
import {Inputs} from './inputs';
import {Install} from './install';
import {Cert} from '../types/buildx';
@@ -32,18 +32,18 @@ export interface BuildxOpts {
}
export class Buildx {
private readonly context: Context;
private _version: string | undefined;
private readonly _standalone: boolean | undefined;
private readonly context: Context;
public readonly inputs: Inputs;
public readonly install: Install;
public readonly standalone: boolean;
public static readonly containerNamePrefix = 'buildx_buildkit_';
constructor(opts: BuildxOpts) {
this._standalone = opts?.standalone;
this.context = opts.context;
this.inputs = new Inputs(this.context);
this.install = new Install({standalone: opts.standalone});
this.standalone = opts?.standalone ?? !Docker.isAvailable;
}
static get configDir(): string {
@@ -54,34 +54,46 @@ export class Buildx {
return path.join(Buildx.configDir, 'certs');
}
public getCommand(args: Array<string>) {
public async isStandalone(): Promise<boolean> {
const standalone = this._standalone ?? !(await Docker.isAvailable());
core.debug(`Buildx.isStandalone: ${standalone}`);
return standalone;
}
public async getCommand(args: Array<string>) {
const standalone = await this.isStandalone();
return {
command: this.standalone ? 'buildx' : 'docker',
args: this.standalone ? args : ['buildx', ...args]
command: standalone ? 'buildx' : 'docker',
args: standalone ? args : ['buildx', ...args]
};
}
public async isAvailable(): Promise<boolean> {
const cmd = this.getCommand([]);
return await exec
const cmd = await this.getCommand([]);
const ok: boolean = await 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}`);
return false;
}
return res.exitCode == 0;
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.catch(error => {
core.debug(`Buildx.isAvailable error: ${error}`);
return false;
});
core.debug(`Buildx.isAvailable: ${ok}`);
return ok;
}
public async printInspect(name: string): Promise<void> {
const cmd = this.getCommand(['inspect', name]);
const cmd = await this.getCommand(['inspect', name]);
await exec.exec(cmd.command, cmd.args, {
failOnStdErr: false
});
@@ -90,7 +102,7 @@ export class Buildx {
get version() {
return (async () => {
if (!this._version) {
const cmd = this.getCommand(['version']);
const cmd = await this.getCommand(['version']);
this._version = await exec
.getExecOutput(cmd.command, cmd.args, {
ignoreReturnCode: true,
@@ -108,7 +120,7 @@ export class Buildx {
}
public async printVersion() {
const cmd = this.getCommand(['version']);
const cmd = await this.getCommand(['version']);
await exec.exec(cmd.command, cmd.args, {
failOnStdErr: false
});
@@ -125,9 +137,12 @@ export class Buildx {
public async versionSatisfies(range: string, version?: string): Promise<boolean> {
const ver = version ?? (await this.version);
if (!ver) {
core.debug(`Buildx.versionSatisfies false: undefined version`);
return false;
}
return semver.satisfies(ver, range) || /^[0-9a-f]{7}$/.exec(ver) !== null;
const res = semver.satisfies(ver, range) || /^[0-9a-f]{7}$/.exec(ver) !== null;
core.debug(`Buildx.versionSatisfies ${ver} statisfies ${range}: ${res}`);
return res;
}
public static resolveCertsDriverOpts(driver: string, endpoint: string, cert: Cert): Array<string> {

View File

@@ -29,11 +29,11 @@ export class Inputs {
}
public getBuildImageIDFilePath(): string {
return path.join(this.context.tmpDir(), 'iidfile').split(path.sep).join(path.posix.sep);
return path.join(this.context.tmpDir(), 'iidfile');
}
public getBuildMetadataFilePath(): string {
return path.join(this.context.tmpDir(), 'metadata-file').split(path.sep).join(path.posix.sep);
return path.join(this.context.tmpDir(), 'metadata-file');
}
public resolveBuildImageID(): string | undefined {

View File

@@ -18,27 +18,39 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as httpm from '@actions/http-client';
import * as tc from '@actions/tool-cache';
import * as semver from 'semver';
import * as util from 'util';
import {Buildx} from './buildx';
import {Context} from '../context';
import {Docker} from '../docker';
import {Git} from '../git';
import {GitHubRelease} from '../types/github';
export interface InstallOpts {
context?: Context;
standalone?: boolean;
}
export class Install {
private readonly opts: InstallOpts;
private readonly _standalone: boolean | undefined;
private readonly context: Context;
constructor(opts?: InstallOpts) {
this.opts = opts || {};
this.context = opts?.context || new Context();
this._standalone = opts?.standalone;
}
public async install(version: string, dest: string): Promise<string> {
public async download(version: string): Promise<string> {
const release: GitHubRelease = await Install.getRelease(version);
const fversion = release.tag_name.replace(/^v+|v+$/g, '');
core.debug(`Install.download version: ${fversion}`);
let toolPath: string;
toolPath = tc.find('buildx', fversion, this.platform());
if (!toolPath) {
@@ -46,15 +58,52 @@ export class Install {
if (!semver.valid(c)) {
throw new Error(`Invalid Buildx version "${fversion}".`);
}
toolPath = await this.download(fversion);
toolPath = await this.fetchBinary(fversion);
}
if (this.opts.standalone) {
return this.setStandalone(toolPath, dest);
}
return this.setPlugin(toolPath, dest);
core.debug(`Install.download toolPath: ${toolPath}`);
return toolPath;
}
private async setStandalone(toolPath: string, dest: string): Promise<string> {
public async build(gitContext: string): Promise<string> {
// eslint-disable-next-line prefer-const
let [repo, ref] = gitContext.split('#');
if (ref.length == 0) {
ref = 'master';
}
let vspec: string;
// TODO: include full ref as fingerprint. Use commit sha as best-effort in the meantime.
if (ref.match(/^[0-9a-fA-F]{40}$/)) {
vspec = ref;
} else {
vspec = await Git.getRemoteSha(repo, ref);
}
core.debug(`Install.build: tool version spec ${vspec}`);
let toolPath: string;
toolPath = tc.find('buildx', vspec);
if (!toolPath) {
const outputDir = path.join(this.context.tmpDir(), 'build-cache');
const buildCmd = await this.buildCommand(gitContext, outputDir);
toolPath = await exec
.getExecOutput(buildCmd.command, buildCmd.args, {
ignoreReturnCode: true
})
.then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
core.warning(res.stderr.trim());
}
return tc.cacheFile(`${outputDir}/buildx`, os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx', 'buildx', vspec);
});
}
return toolPath;
}
public async installStandalone(toolPath: string, dest?: string): Promise<string> {
core.info('Standalone mode');
dest = dest || this.context.tmpDir();
const toolBinPath = path.join(toolPath, os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx');
const binDir = path.join(dest, 'bin');
if (!fs.existsSync(binDir)) {
@@ -63,12 +112,20 @@ export class Install {
const filename: string = os.platform() == 'win32' ? 'buildx.exe' : 'buildx';
const buildxPath: string = path.join(binDir, filename);
fs.copyFileSync(toolBinPath, buildxPath);
core.info('Fixing perms');
fs.chmodSync(buildxPath, '0755');
core.addPath(binDir);
core.info('Added Buildx to PATH');
core.info(`Binary path: ${buildxPath}`);
return buildxPath;
}
private async setPlugin(toolPath: string, dest: string): Promise<string> {
public async installPlugin(toolPath: string, dest?: string): Promise<string> {
core.info('Docker plugin mode');
dest = dest || Docker.configDir;
const toolBinPath = path.join(toolPath, os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx');
const pluginsDir: string = path.join(dest, 'cli-plugins');
if (!fs.existsSync(pluginsDir)) {
@@ -77,16 +134,57 @@ export class Install {
const filename: string = os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx';
const pluginPath: string = path.join(pluginsDir, filename);
fs.copyFileSync(toolBinPath, pluginPath);
core.info('Fixing perms');
fs.chmodSync(pluginPath, '0755');
core.info(`Plugin path: ${pluginPath}`);
return pluginPath;
}
private async download(version: string): Promise<string> {
private async buildCommand(gitContext: string, outputDir: string): Promise<{args: Array<string>; command: string}> {
const buildxStandaloneFound = await new Buildx({context: this.context, standalone: true}).isAvailable();
const buildxPluginFound = await new Buildx({context: this.context, standalone: false}).isAvailable();
let buildStandalone = false;
if ((await this.isStandalone()) && buildxStandaloneFound) {
core.debug(`Install.buildCommand: Buildx standalone found, build with it`);
buildStandalone = true;
} else if (!(await 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}`);
}
//prettier-ignore
return await new Buildx({context: this.context, standalone: buildStandalone}).getCommand([
'build',
'--target', 'binaries',
'--build-arg', 'BUILDKIT_CONTEXT_KEEP_GIT_DIR=1',
'--output', `type=local,dest=${outputDir}`,
gitContext
]);
}
private async isStandalone(): Promise<boolean> {
const standalone = this._standalone ?? !(await Docker.isAvailable());
core.debug(`Install.isStandalone: ${standalone}`);
return standalone;
}
private async fetchBinary(version: string): Promise<string> {
const targetFile: string = os.platform() == 'win32' ? 'docker-buildx.exe' : 'docker-buildx';
const downloadURL = util.format('https://github.com/docker/buildx/releases/download/v%s/%s', version, this.filename(version));
core.info(`Downloading ${downloadURL}`);
const downloadPath = await tc.downloadTool(downloadURL);
core.debug(`downloadURL: ${downloadURL}`);
core.debug(`downloadPath: ${downloadPath}`);
core.debug(`Install.fetchBinary downloadPath: ${downloadPath}`);
return await tc.cacheFile(downloadPath, targetFile, 'buildx', version);
}

View File

@@ -27,7 +27,7 @@ export class Context {
public buildGitContext: string;
public provenanceBuilderID: string;
private readonly _tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'docker-actions-toolkit-')).split(path.sep).join(path.posix.sep);
private readonly _tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'docker-actions-toolkit-'));
constructor() {
this.gitRef = github.context.ref;

View File

@@ -16,6 +16,7 @@
import os from 'os';
import path from 'path';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
export class Docker {
@@ -23,44 +24,33 @@ export class Docker {
return process.env.DOCKER_CONFIG || path.join(os.homedir(), '.docker');
}
static get isAvailable(): boolean {
let dockerAvailable = false;
exec
public static async isAvailable(): Promise<boolean> {
const ok: boolean = await exec
.getExecOutput('docker', undefined, {
ignoreReturnCode: true,
silent: true
})
.then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
dockerAvailable = false;
} else {
dockerAvailable = res.exitCode == 0;
core.debug(`Docker.isAvailable cmd err: ${res.stderr}`);
return false;
}
return res.exitCode == 0;
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.catch(error => {
dockerAvailable = false;
core.debug(`Docker.isAvailable error: ${error}`);
return false;
});
return dockerAvailable;
core.debug(`Docker.isAvailable: ${ok}`);
return ok;
}
public static async printVersion(standalone?: boolean) {
const noDocker = standalone ?? !Docker.isAvailable;
if (noDocker) {
return;
}
await exec.exec('docker', ['version'], {
failOnStdErr: false
});
public static async printVersion(): Promise<void> {
await exec.exec('docker', ['version']);
}
public static async printInfo(standalone?: boolean) {
const noDocker = standalone ?? !Docker.isAvailable;
if (noDocker) {
return;
}
await exec.exec('docker', ['info'], {
failOnStdErr: false
});
public static async printInfo(): Promise<void> {
await exec.exec('docker', ['info']);
}
}

View File

@@ -16,6 +16,8 @@
import {Context} from './context';
import {Buildx} from './buildx/buildx';
import {Install} from './buildx/install';
import {Builder} from './buildx/builder';
import {BuildKit} from './buildkit/buildkit';
import {GitHub} from './github';
@@ -31,12 +33,16 @@ export class Toolkit {
public context: Context;
public github: GitHub;
public buildx: Buildx;
public buildxInstall: Install;
public builder: Builder;
public buildkit: BuildKit;
constructor(opts: ToolkitOpts = {}) {
this.context = new Context();
this.github = new GitHub({token: opts.githubToken});
this.buildx = new Buildx({context: this.context});
this.buildxInstall = new Install({context: this.context});
this.builder = new Builder({context: this.context, buildx: this.buildx});
this.buildkit = new BuildKit({context: this.context, buildx: this.buildx});
}
}

View File

@@ -30,3 +30,11 @@ export interface NodeInfo {
buildkitVersion?: string;
platforms?: string;
}
export interface Node {
name?: string;
endpoint?: string;
'driver-opts'?: Array<string>;
'buildkitd-flags'?: string;
platforms?: string;
}

View File

@@ -17,8 +17,13 @@
import * as core from '@actions/core';
import {parse} from 'csv-parse/sync';
export interface InputListOpts {
ignoreComma?: boolean;
quote?: string | boolean | Buffer | null;
}
export class Util {
public static getInputList(name: string, ignoreComma?: boolean): string[] {
public static getInputList(name: string, opts?: InputListOpts): string[] {
const res: Array<string> = [];
const items = core.getInput(name);
@@ -31,18 +36,22 @@ export class Util {
relaxQuotes: true,
comment: '#',
relaxColumnCount: true,
skipEmptyLines: true
skipEmptyLines: true,
quote: opts?.quote
});
for (const record of records as Array<string[]>) {
if (record.length == 1) {
res.push(record[0]);
continue;
} else if (!ignoreComma) {
if (opts?.ignoreComma) {
res.push(record[0]);
} else {
res.push(...record[0].split(','));
}
} else if (!opts?.ignoreComma) {
res.push(...record);
continue;
} else {
res.push(record.join(','));
}
res.push(record.join(','));
}
return res.filter(item => item).map(pat => pat.trim());