Skip to content

Commit

Permalink
switch to actions-toolkit implementation
Browse files Browse the repository at this point in the history
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
  • Loading branch information
CrazyMax committed Feb 24, 2023
1 parent 3da7dc6 commit af023e8
Show file tree
Hide file tree
Showing 10 changed files with 272 additions and 88 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"env": {
"node": true,
"es2021": true,
"jest/globals": true
"jest": true
},
"extends": [
"eslint:recommended",
Expand Down
5 changes: 0 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
/.dev
node_modules/
lib

# Jetbrains
/.idea
/*.iml

# Rest of the file pulled from https://github.com/github/gitignore/blob/master/Node.gitignore
# Logs
logs
Expand Down
13 changes: 4 additions & 9 deletions __tests__/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import {expect, jest, test} from '@jest/globals';
import osm = require('os');

import {run} from '../src/main';
import {main} from '../src/main';
import * as docker from '../src/docker';
import * as stateHelper from '../src/state-helper';

import * as core from '@actions/core';

test('errors without username and password', async () => {
jest.spyOn(osm, 'platform').mockImplementation(() => 'linux');
process.env['INPUT_LOGOUT'] = 'true'; // default value
const coreSpy = jest.spyOn(core, 'setFailed');

await run();
expect(coreSpy).toHaveBeenCalledWith('Username and password required');
await expect(main()).rejects.toThrowError(new Error('Username and password required'));
});

test('successful with username and password', async () => {
Expand All @@ -34,7 +29,7 @@ test('successful with username and password', async () => {
const logout = false;
process.env['INPUT_LOGOUT'] = String(logout);

await run();
await main();

expect(setRegistrySpy).toHaveBeenCalledWith('');
expect(setLogoutSpy).toHaveBeenCalledWith(logout);
Expand Down Expand Up @@ -63,7 +58,7 @@ test('calls docker login', async () => {
const logout = true;
process.env['INPUT_LOGOUT'] = String(logout);

await run();
await main();

expect(setRegistrySpy).toHaveBeenCalledWith(registry);
expect(setLogoutSpy).toHaveBeenCalledWith(logout);
Expand Down
23 changes: 21 additions & 2 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,29 @@
import fs from 'fs';
import os from 'os';
import path from 'path';

const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'docker-login-action-')).split(path.sep).join(path.posix.sep);

process.env = Object.assign({}, process.env, {
TEMP: tmpDir,
GITHUB_REPOSITORY: 'docker/login-action',
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)
}) as {
[key: string]: string;
};

module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
setupFiles: ["dotenv/config"],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.ts$': 'ts-jest'
},
moduleNameMapper: {
'^csv-parse/sync': '<rootDir>/node_modules/csv-parse/dist/cjs/sync.cjs'
},
collectCoverageFrom: ['src/**/{!(main.ts),}.ts'],
coveragePathIgnorePatterns: ['lib/', 'node_modules/', '__tests__/'],
verbose: true
}
};
4 changes: 1 addition & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,9 @@
"license": "MIT",
"dependencies": {
"@actions/core": "^1.10.0",
"@actions/exec": "^1.1.1",
"@actions/io": "^1.1.2",
"@aws-sdk/client-ecr": "^3.231.0",
"@aws-sdk/client-ecr-public": "^3.231.0",
"@docker/actions-toolkit": "^0.1.0-beta.14",
"http-proxy-agent": "^5.0.0",
"https-proxy-agent": "^5.0.1"
},
Expand All @@ -40,7 +39,6 @@
"@typescript-eslint/eslint-plugin": "^5.14.0",
"@typescript-eslint/parser": "^5.14.0",
"@vercel/ncc": "^0.33.3",
"dotenv": "^16.0.0",
"eslint": "^8.11.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-jest": "^26.1.1",
Expand Down
62 changes: 28 additions & 34 deletions src/docker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as aws from './aws';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import {Exec} from '@docker/actions-toolkit/lib/exec';

export async function login(registry: string, username: string, password: string, ecr: string): Promise<void> {
if (/true/i.test(ecr) || (ecr == 'auto' && aws.isECR(registry))) {
Expand All @@ -11,15 +11,13 @@ export async function login(registry: string, username: string, password: string
}

export async function logout(registry: string): Promise<void> {
await exec
.getExecOutput('docker', ['logout', registry], {
ignoreReturnCode: true
})
.then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
core.warning(res.stderr.trim());
}
});
await Exec.getExecOutput('docker', ['logout', registry], {
ignoreReturnCode: true
}).then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
core.warning(res.stderr.trim());
}
});
}

export async function loginStandard(registry: string, username: string, password: string): Promise<void> {
Expand All @@ -36,36 +34,32 @@ export async function loginStandard(registry: string, username: string, password
} else {
core.info(`Logging into Docker Hub...`);
}
await exec
.getExecOutput('docker', loginArgs, {
ignoreReturnCode: true,
silent: true,
input: Buffer.from(password)
})
.then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
throw new Error(res.stderr.trim());
}
core.info(`Login Succeeded!`);
});
await Exec.getExecOutput('docker', loginArgs, {
ignoreReturnCode: true,
silent: true,
input: Buffer.from(password)
}).then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
throw new Error(res.stderr.trim());
}
core.info(`Login Succeeded!`);
});
}

export async function loginECR(registry: string, username: string, password: string): Promise<void> {
core.info(`Retrieving registries data through AWS SDK...`);
const regDatas = await aws.getRegistriesData(registry, username, password);
for (const regData of regDatas) {
core.info(`Logging into ${regData.registry}...`);
await exec
.getExecOutput('docker', ['login', '--password-stdin', '--username', regData.username, regData.registry], {
ignoreReturnCode: true,
silent: true,
input: Buffer.from(regData.password)
})
.then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
throw new Error(res.stderr.trim());
}
core.info('Login Succeeded!');
});
await Exec.getExecOutput('docker', ['login', '--password-stdin', '--username', regData.username, regData.registry], {
ignoreReturnCode: true,
silent: true,
input: Buffer.from(regData.password)
}).then(res => {
if (res.stderr.length > 0 && res.exitCode != 0) {
throw new Error(res.stderr.trim());
}
core.info('Login Succeeded!');
});
}
}
25 changes: 9 additions & 16 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,21 @@
import * as core from '@actions/core';
import * as actionsToolkit from '@docker/actions-toolkit';

import * as context from './context';
import * as docker from './docker';
import * as stateHelper from './state-helper';

export async function run(): Promise<void> {
try {
const input: context.Inputs = context.getInputs();
stateHelper.setRegistry(input.registry);
stateHelper.setLogout(input.logout);
await docker.login(input.registry, input.username, input.password, input.ecr);
} catch (error) {
core.setFailed(error.message);
}
export async function main(): Promise<void> {
const input: context.Inputs = context.getInputs();
stateHelper.setRegistry(input.registry);
stateHelper.setLogout(input.logout);
await docker.login(input.registry, input.username, input.password, input.ecr);
}

async function logout(): Promise<void> {
async function post(): Promise<void> {
if (!stateHelper.logout) {
return;
}
await docker.logout(stateHelper.registry);
}

if (!stateHelper.IsPost) {
run();
} else {
logout();
}
actionsToolkit.run(main, post);
5 changes: 0 additions & 5 deletions src/state-helper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as core from '@actions/core';

export const IsPost = !!process.env['STATE_isPost'];
export const registry = process.env['STATE_registry'] || '';
export const logout = /true/i.test(process.env['STATE_logout'] || '');

Expand All @@ -11,7 +10,3 @@ export function setRegistry(registry: string) {
export function setLogout(logout: boolean) {
core.saveState('logout', logout);
}

if (!IsPost) {
core.saveState('isPost', 'true');
}
8 changes: 5 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
{
"compilerOptions": {
"esModuleInterop": true,
"target": "es6",
"module": "commonjs",
"strict": true,
"newLine": "lf",
"outDir": "./lib",
"rootDir": "./src",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": false,
"resolveJsonModule": true,
"useUnknownInCatchVariables": false,
},
"exclude": [
"./__tests__/**/*",
"./lib/**/*",
"node_modules",
"**/*.test.ts",
"jest.config.ts"
]
}
Loading

0 comments on commit af023e8

Please sign in to comment.