Merge pull request #6493 from getndazn/feat/scaffolder-gha-dispatch

[Scaffolder] New built-in action for GitHub Actions
This commit is contained in:
Ben Lambert
2021-07-21 20:08:31 +02:00
committed by GitHub
8 changed files with 271 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-scaffolder-backend': patch
---
Add new built-in action ci:github-actions-dispatch
+7
View File
@@ -107,6 +107,13 @@ export const createFilesystemDeleteAction: () => TemplateAction<any>;
// @public (undocumented)
export const createFilesystemRenameAction: () => TemplateAction<any>;
// Warning: (ae-missing-release-tag) "createGithubActionsDispatchAction" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
export function createGithubActionsDispatchAction(options: {
integrations: ScmIntegrationRegistry;
}): TemplateAction<any>;
// Warning: (ae-missing-release-tag) "createPublishAzureAction" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
//
// @public (undocumented)
@@ -15,6 +15,11 @@
*/
export const mockGithubClient = {
rest: {
actions: {
createWorkflowDispatch: jest.fn(),
},
},
repos: {
createInOrg: jest.fn(),
createForAuthenticatedUser: jest.fn(),
@@ -37,6 +37,7 @@ import {
createPublishGithubPullRequestAction,
createPublishGitlabAction,
} from './publish';
import { createGithubActionsDispatchAction } from './github';
export const createBuiltinActions = (options: {
reader: UrlReader;
@@ -91,5 +92,8 @@ export const createBuiltinActions = (options: {
createCatalogWriteAction(),
createFilesystemDeleteAction(),
createFilesystemRenameAction(),
createGithubActionsDispatchAction({
integrations,
}),
];
};
@@ -0,0 +1,117 @@
/*
* Copyright 2021 The Backstage 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.
*/
jest.mock('@octokit/rest');
import { createGithubActionsDispatchAction } from './githubActionsDispatch';
import { ScmIntegrations } from '@backstage/integration';
import { ConfigReader } from '@backstage/config';
import { getVoidLogger } from '@backstage/backend-common';
import { PassThrough } from 'stream';
describe('github:actions:dispatch', () => {
const config = new ConfigReader({
integrations: {
github: [
{ host: 'github.com', token: 'tokenlols' },
{ host: 'ghe.github.com' },
],
},
});
const integrations = ScmIntegrations.fromConfig(config);
const action = createGithubActionsDispatchAction({ integrations });
const mockContext = {
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
workflowId: 'a-workflow-id',
branchOrTagName: 'main',
},
workspacePath: 'lol',
logger: getVoidLogger(),
logStream: new PassThrough(),
output: jest.fn(),
createTemporaryDirectory: jest.fn(),
};
const { mockGithubClient } = require('@octokit/rest');
beforeEach(() => {
jest.resetAllMocks();
});
it('should throw an error when the repoUrl is not well formed', async () => {
await expect(
action.handler({
...mockContext,
input: { repoUrl: 'github.com?repo=bob' },
}),
).rejects.toThrow(/missing owner/);
await expect(
action.handler({
...mockContext,
input: { repoUrl: 'github.com?owner=owner' },
}),
).rejects.toThrow(/missing repo/);
});
it('should throw if there is no integration config provided', async () => {
await expect(
action.handler({
...mockContext,
input: { repoUrl: 'missing.com?repo=bob&owner=owner' },
}),
).rejects.toThrow(/No matching integration configuration/);
});
it('should throw if there is no token in the integration config that is returned', async () => {
await expect(
action.handler({
...mockContext,
input: {
repoUrl: 'ghe.github.com?repo=bob&owner=owner',
},
}),
).rejects.toThrow(/No token available for host/);
});
it('should call the githubApis for creating WorkflowDispatch', async () => {
mockGithubClient.rest.actions.createWorkflowDispatch.mockResolvedValue({
data: {
foo: 'bar',
},
});
const repoUrl = 'github.com?repo=repo&owner=owner';
const workflowId = 'dispatch_workflow';
const branchOrTagName = 'main';
const ctx = Object.assign({}, mockContext, {
input: { repoUrl, workflowId, branchOrTagName },
});
await action.handler(ctx);
expect(
mockGithubClient.rest.actions.createWorkflowDispatch,
).toHaveBeenCalledWith({
owner: 'owner',
repo: 'repo',
workflow_id: workflowId,
ref: branchOrTagName,
});
});
});
@@ -0,0 +1,115 @@
/*
* Copyright 2021 The Backstage 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 { InputError } from '@backstage/errors';
import {
GithubCredentialsProvider,
ScmIntegrationRegistry,
} from '@backstage/integration';
import { Octokit } from '@octokit/rest';
import { parseRepoUrl } from '../publish/util';
import { createTemplateAction } from '../../createTemplateAction';
export function createGithubActionsDispatchAction(options: {
integrations: ScmIntegrationRegistry;
}) {
const { integrations } = options;
const credentialsProviders = new Map(
integrations.github.list().map(integration => {
const provider = GithubCredentialsProvider.create(integration.config);
return [integration.config.host, provider];
}),
);
return createTemplateAction<{
repoUrl: string;
workflowId: string;
branchOrTagName: string;
}>({
id: 'github:actions:dispatch',
description:
'Dispatches a GitHub Action workflow for a given branch or tag',
schema: {
input: {
type: 'object',
required: ['repoUrl', 'workflowId', 'branchOrTagName'],
properties: {
repoUrl: {
title: 'Repository Location',
description: `Accepts the format 'github.com?repo=reponame&owner=owner' where 'reponame' is the new repository name and 'owner' is an organization or username`,
type: 'string',
},
workflowId: {
title: 'Workflow ID',
description: 'The GitHub Action Workflow filename',
type: 'string',
},
branchOrTagName: {
title: 'Branch or Tag name',
description:
'The git branch or tag name used to dispatch the workflow',
type: 'string',
},
},
},
},
async handler(ctx) {
const { repoUrl, workflowId, branchOrTagName } = ctx.input;
const { owner, repo, host } = parseRepoUrl(repoUrl);
ctx.logger.info(
`Dispatching workflow ${workflowId} for repo ${repoUrl} on ${branchOrTagName}`,
);
const credentialsProvider = credentialsProviders.get(host);
const integrationConfig = integrations.github.byHost(host);
if (!credentialsProvider || !integrationConfig) {
throw new InputError(
`No matching integration configuration for host ${host}, please check your integrations config`,
);
}
const { token } = await credentialsProvider.getCredentials({
url: `https://${host}/${encodeURIComponent(owner)}/${encodeURIComponent(
repo,
)}`,
});
if (!token) {
throw new InputError(
`No token available for host: ${host}, with owner ${owner}, and repo ${repo}`,
);
}
const client = new Octokit({
auth: token,
baseUrl: integrationConfig.config.apiBaseUrl,
previews: ['nebula-preview'],
});
await client.rest.actions.createWorkflowDispatch({
owner,
repo,
workflow_id: workflowId,
ref: branchOrTagName,
});
ctx.logger.info(`Workflow ${workflowId} dispatched successfully`);
},
});
}
@@ -0,0 +1,17 @@
/*
* Copyright 2021 The Backstage 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 { createGithubActionsDispatchAction } from './githubActionsDispatch';
@@ -20,6 +20,7 @@ export * from './debug';
export * from './fetch';
export * from './filesystem';
export * from './publish';
export * from './github';
export { createFetchCookiecutterAction } from '@backstage/plugin-scaffolder-backend-module-cookiecutter';
export { runCommand } from './helpers';