Merge pull request #19379 from tperehinets/scaffolder-action-examples

Added description for publish:github and publish:gitlab scaffolder actions.
This commit is contained in:
Fredrik Adelöw
2023-08-16 09:20:30 +02:00
committed by GitHub
7 changed files with 416 additions and 0 deletions
@@ -0,0 +1,151 @@
/*
* 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('../helpers');
import { TemplateAction } from '@backstage/plugin-scaffolder-node';
import { getVoidLogger } from '@backstage/backend-common';
import { ConfigReader } from '@backstage/config';
import {
DefaultGithubCredentialsProvider,
GithubCredentialsProvider,
ScmIntegrations,
} from '@backstage/integration';
import { PassThrough } from 'stream';
import { entityRefToName, initRepoAndPush } from '../helpers';
import { createPublishGithubAction } from './github';
import { examples } from './github.examples';
import yaml from 'yaml';
const publicKey = '2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvvcCU=';
const initRepoAndPushMocked = initRepoAndPush as jest.Mock<
Promise<{ commitHash: string }>
>;
const mockOctokit = {
rest: {
users: {
getByUsername: jest.fn(),
},
repos: {
addCollaborator: jest.fn(),
createInOrg: jest.fn(),
createForAuthenticatedUser: jest.fn(),
replaceAllTopics: jest.fn(),
},
teams: {
getByName: jest.fn(),
addOrUpdateRepoPermissionsInOrg: jest.fn(),
},
actions: {
createRepoVariable: jest.fn(),
createOrUpdateRepoSecret: jest.fn(),
getRepoPublicKey: jest.fn(),
},
},
};
jest.mock('octokit', () => ({
Octokit: class {
constructor() {
return mockOctokit;
}
},
}));
describe('publish:github', () => {
const config = new ConfigReader({
integrations: {
github: [
{ host: 'github.com', token: 'tokenlols' },
{ host: 'ghe.github.com' },
],
},
});
const { entityRefToName: realFamiliarizeEntityName } =
jest.requireActual('../helpers');
const integrations = ScmIntegrations.fromConfig(config);
let githubCredentialsProvider: GithubCredentialsProvider;
let action: TemplateAction<any>;
const mockContext = {
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
description: 'description',
repoVisibility: 'private' as const,
access: 'owner/blam',
},
workspacePath: 'lol',
logger: getVoidLogger(),
logStream: new PassThrough(),
output: jest.fn(),
createTemporaryDirectory: jest.fn(),
};
beforeEach(() => {
initRepoAndPushMocked.mockResolvedValue({
commitHash: '220f19cc36b551763d157f1b5e4a4b446165dbd6',
});
githubCredentialsProvider =
DefaultGithubCredentialsProvider.fromIntegrations(integrations);
action = createPublishGithubAction({
integrations,
config,
githubCredentialsProvider,
});
// restore real implmentation
(entityRefToName as jest.Mock).mockImplementation(
realFamiliarizeEntityName,
);
mockOctokit.rest.actions.getRepoPublicKey.mockResolvedValue({
data: {
key: publicKey,
key_id: 'keyid',
},
});
});
afterEach(jest.resetAllMocks);
it('should call initRepoAndPush with the correct values', async () => {
mockOctokit.rest.users.getByUsername.mockResolvedValue({
data: { type: 'User' },
});
mockOctokit.rest.repos.createForAuthenticatedUser.mockResolvedValue({
data: {
clone_url: 'https://github.com/clone/url.git',
html_url: 'https://github.com/html/url',
},
});
await action.handler({
...mockContext,
input: yaml.parse(examples[0].example).steps[0].input,
});
expect(initRepoAndPush).toHaveBeenCalledWith({
dir: mockContext.workspacePath,
remoteUrl: 'https://github.com/clone/url.git',
defaultBranch: 'master',
auth: { username: 'x-access-token', password: 'tokenlols' },
logger: mockContext.logger,
commitMessage: 'initial commit',
gitAuthorInfo: {},
});
});
});
@@ -0,0 +1,70 @@
/*
* Copyright 2023 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 { TemplateExample } from '@backstage/plugin-scaffolder-node';
import yaml from 'yaml';
export const examples: TemplateExample[] = [
{
description:
'Initializes a git repository of contents in workspace and publish it to GitHub with default configuration.',
example: yaml.stringify({
steps: [
{
id: 'publish',
action: 'publish:github',
name: 'Publish to GitHub',
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
},
},
],
}),
},
{
description: 'Add a description.',
example: yaml.stringify({
steps: [
{
id: 'publish',
action: 'publish:github',
name: 'Publish to GitHub',
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
description: 'Initialize a git repository',
},
},
],
}),
},
{
description: 'Change visibility of the repository.',
example: yaml.stringify({
steps: [
{
id: 'publish',
action: 'publish:github',
name: 'Publish to GitHub',
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
description: 'Initialize a git repository',
repoVisibility: 'public',
},
},
],
}),
},
];
@@ -30,6 +30,7 @@ import {
import * as inputProps from '../github/inputProperties';
import * as outputProps from '../github/outputProperties';
import { parseRepoUrl } from './util';
import { examples } from './github.examples';
/**
* Creates a new action that initializes a git repository of the content in the workspace
@@ -111,6 +112,7 @@ export function createPublishGithubAction(options: {
id: 'publish:github',
description:
'Initializes a git repository of contents in workspace and publishes it to GitHub.',
examples,
schema: {
input: {
type: 'object',
@@ -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 yaml from 'yaml';
jest.mock('../helpers', () => {
return {
initRepoAndPush: jest.fn().mockResolvedValue({
commitHash: '220f19cc36b551763d157f1b5e4a4b446165dbd6',
}),
commitAndPushRepo: jest.fn().mockResolvedValue({
commitHash: '220f19cc36b551763d157f1b5e4a4b446165dbd6',
}),
};
});
import { createPublishGitlabAction } from './gitlab';
import { ScmIntegrations } from '@backstage/integration';
import { ConfigReader } from '@backstage/config';
import { getVoidLogger } from '@backstage/backend-common';
import { PassThrough } from 'stream';
import { initRepoAndPush } from '../helpers';
import { examples } from './gitlab.examples';
const mockGitlabClient = {
Namespaces: {
show: jest.fn(),
},
Projects: {
create: jest.fn(),
},
Users: {
current: jest.fn(),
},
ProjectMembers: {
add: jest.fn(),
},
};
jest.mock('@gitbeaker/node', () => ({
Gitlab: class {
constructor() {
return mockGitlabClient;
}
},
}));
describe('publish:gitlab', () => {
const config = new ConfigReader({
integrations: {
gitlab: [
{
host: 'gitlab.com',
token: 'tokenlols',
apiBaseUrl: 'https://api.gitlab.com',
},
{
host: 'hosted.gitlab.com',
apiBaseUrl: 'https://api.hosted.gitlab.com',
},
],
},
});
const integrations = ScmIntegrations.fromConfig(config);
const action = createPublishGitlabAction({ integrations, config });
const mockContext = {
input: {
repoUrl: 'gitlab.com?repo=repo&owner=owner',
},
workspacePath: 'lol',
logger: getVoidLogger(),
logStream: new PassThrough(),
output: jest.fn(),
createTemporaryDirectory: jest.fn(),
};
beforeEach(() => {
jest.resetAllMocks();
});
it('should call initRepoAndPush with the correct values', async () => {
mockGitlabClient.Users.current.mockResolvedValue({ id: 12345 });
mockGitlabClient.Namespaces.show.mockResolvedValue({ id: 1234 });
mockGitlabClient.Projects.create.mockResolvedValue({
http_url_to_repo: 'http://mockurl.git',
});
await action.handler({
...mockContext,
input: yaml.parse(examples[0].example).steps[0].input,
});
expect(initRepoAndPush).toHaveBeenCalledWith({
dir: mockContext.workspacePath,
defaultBranch: 'master',
remoteUrl: 'http://mockurl.git',
auth: { username: 'oauth2', password: 'tokenlols' },
logger: mockContext.logger,
commitMessage: 'initial commit',
gitAuthorInfo: {},
});
});
});
@@ -0,0 +1,71 @@
/*
* Copyright 2023 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 { TemplateExample } from '@backstage/plugin-scaffolder-node';
import yaml from 'yaml';
export const examples: TemplateExample[] = [
{
description:
'Initializes a git repository of the content in the workspace, and publishes it to GitLab.',
example: yaml.stringify({
steps: [
{
id: 'publish',
action: 'publish:gitlab',
name: 'Publish to GitLab',
input: {
repoUrl: 'gitlab.com?repo=project_name&owner=group_name',
},
},
],
}),
},
{
description: 'Add a description.',
example: yaml.stringify({
steps: [
{
id: 'publish',
action: 'publish:gitlab',
name: 'Publish to GitLab',
input: {
repoUrl: 'gitlab.com?repo=project_name&owner=group_name',
description: 'Initialize a git repository',
},
},
],
}),
},
{
description:
'Sets the commit message on the repository. The default value is `initial commit`.',
example: yaml.stringify({
steps: [
{
id: 'publish',
action: 'publish:gitlab',
name: 'Publish to GitLab',
input: {
repoUrl: 'gitlab.com?repo=project_name&owner=group_name',
description: 'Initialize a git repository',
gitCommitMessage: 'Started a project.',
},
},
],
}),
},
];
@@ -21,6 +21,7 @@ import { Gitlab } from '@gitbeaker/node';
import { initRepoAndPush } from '../helpers';
import { getRepoSourceDirectory, parseRepoUrl } from './util';
import { Config } from '@backstage/config';
import { examples } from './gitlab.examples';
/**
* Creates a new action that initializes a git repository of the content in the workspace
@@ -49,6 +50,7 @@ export function createPublishGitlabAction(options: {
id: 'publish:gitlab',
description:
'Initializes a git repository of the content in the workspace, and publishes it to GitLab.',
examples,
schema: {
input: {
type: 'object',