Merge pull request #19243 from kurtaking/kk/document-github-scaffolder-actions

Add examples for github:repo* scaffolder actions
This commit is contained in:
Patrik Oldsberg
2023-08-12 17:55:18 +02:00
committed by GitHub
7 changed files with 463 additions and 0 deletions
@@ -0,0 +1,192 @@
/*
* 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 { TemplateAction } from '@backstage/plugin-scaffolder-node';
jest.mock('../helpers');
import { getVoidLogger } from '@backstage/backend-common';
import { ConfigReader } from '@backstage/config';
import {
DefaultGithubCredentialsProvider,
GithubCredentialsProvider,
ScmIntegrations,
} from '@backstage/integration';
import { PassThrough } from 'stream';
import { createGithubRepoCreateAction } from './githubRepoCreate';
import { entityRefToName } from '../helpers';
import yaml from 'yaml';
import { examples } from './githubRepoCreate.examples';
const publicKey = '2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvvcCU=';
const mockOctokit = {
rest: {
users: {
getByUsername: jest.fn(),
},
repos: {
addCollaborator: jest.fn(),
createInOrg: jest.fn(),
createForAuthenticatedUser: jest.fn(),
replaceAllTopics: jest.fn(),
},
teams: {
addOrUpdateRepoPermissionsInOrg: jest.fn(),
getByName: jest.fn(),
},
actions: {
createRepoVariable: jest.fn(),
createOrUpdateRepoSecret: jest.fn(),
getRepoPublicKey: jest.fn(),
},
},
};
jest.mock('octokit', () => ({
Octokit: class {
constructor() {
return mockOctokit;
}
},
}));
describe('github:repo:create examples', () => {
const config = new ConfigReader({
integrations: {
github: [
{ host: 'github.com', token: 'tokenlols' },
{ host: 'ghe.github.com' },
],
},
});
const integrations = ScmIntegrations.fromConfig(config);
let githubCredentialsProvider: GithubCredentialsProvider;
let action: TemplateAction<any>;
const mockContext = {
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
},
workspacePath: 'lol',
logger: getVoidLogger(),
logStream: new PassThrough(),
output: jest.fn(),
createTemporaryDirectory: jest.fn(),
};
beforeEach(() => {
githubCredentialsProvider =
DefaultGithubCredentialsProvider.fromIntegrations(integrations);
action = createGithubRepoCreateAction({
integrations,
githubCredentialsProvider,
});
(entityRefToName as jest.Mock).mockImplementation((s: string) => s);
mockOctokit.rest.actions.getRepoPublicKey.mockResolvedValue({
data: {
key: publicKey,
key_id: 'keyid',
},
});
});
afterEach(jest.resetAllMocks);
it('should call the githubApis with the correct values for createInOrg', async () => {
mockOctokit.rest.users.getByUsername.mockResolvedValue({
data: { type: 'Organization' },
});
mockOctokit.rest.repos.createInOrg.mockResolvedValue({ data: {} });
await action.handler({
...mockContext,
input: yaml.parse(examples[0].example).steps[0].input,
});
expect(mockOctokit.rest.repos.createInOrg).toHaveBeenCalledWith({
name: 'repo',
org: 'owner',
private: true,
delete_branch_on_merge: false,
allow_squash_merge: true,
squash_merge_commit_title: 'COMMIT_OR_PR_TITLE',
squash_merge_commit_message: 'COMMIT_MESSAGES',
allow_merge_commit: true,
allow_rebase_merge: true,
allow_auto_merge: false,
visibility: 'private',
});
});
it('should call the githubApis with a description for createInOrg', async () => {
mockOctokit.rest.users.getByUsername.mockResolvedValue({
data: { type: 'Organization' },
});
mockOctokit.rest.repos.createInOrg.mockResolvedValue({ data: {} });
await action.handler({
...mockContext,
input: yaml.parse(examples[1].example).steps[0].input,
});
expect(mockOctokit.rest.repos.createInOrg).toHaveBeenCalledWith({
name: 'repo',
description: 'My new repository',
org: 'owner',
private: true,
delete_branch_on_merge: false,
allow_squash_merge: true,
squash_merge_commit_title: 'COMMIT_OR_PR_TITLE',
squash_merge_commit_message: 'COMMIT_MESSAGES',
allow_merge_commit: true,
allow_rebase_merge: true,
allow_auto_merge: false,
visibility: 'private',
});
});
it('should call the githubApis with wiki and issues disabled for createInOrg', async () => {
mockOctokit.rest.users.getByUsername.mockResolvedValue({
data: { type: 'Organization' },
});
mockOctokit.rest.repos.createInOrg.mockResolvedValue({ data: {} });
await action.handler({
...mockContext,
input: yaml.parse(examples[2].example).steps[0].input,
});
expect(mockOctokit.rest.repos.createInOrg).toHaveBeenCalledWith({
name: 'repo',
org: 'owner',
private: true,
delete_branch_on_merge: false,
allow_squash_merge: true,
squash_merge_commit_title: 'COMMIT_OR_PR_TITLE',
squash_merge_commit_message: 'COMMIT_MESSAGES',
allow_merge_commit: true,
allow_rebase_merge: true,
allow_auto_merge: false,
visibility: 'private',
has_issues: false, // disable issues
has_wiki: false, // disable wiki
});
});
});
@@ -0,0 +1,66 @@
/*
* 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: 'Creates a GitHub repository with default configuration.',
example: yaml.stringify({
steps: [
{
action: 'github:repo:create',
name: 'Create a new GitHub repository',
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
},
},
],
}),
},
{
description: 'Add a description.',
example: yaml.stringify({
steps: [
{
action: 'github:repo:create',
name: 'Create a new GitHub repository with a description',
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
description: 'My new repository',
},
},
],
}),
},
{
description: 'Disable wiki and issues.',
example: yaml.stringify({
steps: [
{
action: 'github:repo:create',
name: 'Create a new GitHub repository without wiki and issues',
input: {
repoUrl: 'github.com?repo=repo&owner=owner',
hasIssues: false,
hasWiki: false,
},
},
],
}),
},
];
@@ -28,6 +28,7 @@ import {
} from './helpers';
import * as inputProps from './inputProperties';
import * as outputProps from './outputProperties';
import { examples } from './githubRepoCreate.examples';
/**
* Creates a new action that initializes a git repository
@@ -96,6 +97,7 @@ export function createGithubRepoCreateAction(options: {
}>({
id: 'github:repo:create',
description: 'Creates a GitHub repository.',
examples,
schema: {
input: {
type: 'object',
@@ -0,0 +1,131 @@
/*
* 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 { 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 { initRepoAndPush } from '../helpers';
import { createGithubRepoPushAction } from './githubRepoPush';
import { examples } from './githubRepoPush.examples';
import yaml from 'yaml';
const mockGit = {
init: jest.fn(),
add: jest.fn(),
checkout: jest.fn(),
commit: jest
.fn()
.mockResolvedValue('220f19cc36b551763d157f1b5e4a4b446165dbd6'),
fetch: jest.fn(),
addRemote: jest.fn(),
push: jest.fn(),
};
jest.mock('@backstage/backend-common', () => ({
Git: {
fromAuth() {
return mockGit;
},
},
getVoidLogger: jest.requireActual('@backstage/backend-common').getVoidLogger,
}));
jest.mock('../helpers');
const initRepoAndPushMocked = initRepoAndPush as jest.Mock<
Promise<{ commitHash: string }>
>;
const mockOctokit = {
rest: {
repos: {
get: jest.fn(),
},
},
};
jest.mock('octokit', () => ({
Octokit: class {
constructor() {
return mockOctokit;
}
},
}));
describe('github:repo:push examples', () => {
const config = new ConfigReader({
integrations: {
github: [
{ host: 'github.com', token: 'tokenlols' },
{ host: 'ghe.github.com' },
],
},
});
const integrations = ScmIntegrations.fromConfig(config);
let githubCredentialsProvider: GithubCredentialsProvider;
let action: TemplateAction<any>;
const mockContext = {
workspacePath: 'lol',
logger: getVoidLogger(),
logStream: new PassThrough(),
output: jest.fn(),
createTemporaryDirectory: jest.fn(),
};
beforeEach(() => {
jest.resetAllMocks();
initRepoAndPushMocked.mockResolvedValue({ commitHash: 'test123' });
githubCredentialsProvider =
DefaultGithubCredentialsProvider.fromIntegrations(integrations);
action = createGithubRepoPushAction({
integrations,
config,
githubCredentialsProvider,
});
});
it('should call initRepoAndPush with the correct values', async () => {
mockOctokit.rest.repos.get.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,65 @@
/*
* 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: 'Setup repo with no modifications to branch protection rules',
example: yaml.stringify({
steps: [
{
action: 'github:repo:push',
name: 'Create test repo with testuser as owner.',
input: {
repoUrl: 'github.com?repo=test&owner=testuser',
},
},
],
}),
},
{
description: 'Setup repo with required codeowners check',
example: yaml.stringify({
steps: [
{
action: 'github:repo:push',
name: 'Require codeowner branch protection rule',
input: {
repoUrl: 'github.com?repo=reponame&owner=owner',
requireCodeOwnerReviews: true,
},
},
],
}),
},
{
description: 'Change the default required number of approvals',
example: yaml.stringify({
steps: [
{
action: 'github:repo:push',
name: 'Require two approvals before merging',
input: {
repoUrl: 'github.com?repo=reponame&owner=owner',
requiredApprovingReviewCount: 2,
},
},
],
}),
},
];
@@ -26,6 +26,7 @@ import { parseRepoUrl } from '../publish/util';
import { getOctokitOptions, initRepoPushAndProtect } from './helpers';
import * as inputProps from './inputProperties';
import * as outputProps from './outputProperties';
import { examples } from './githubRepoPush.examples';
/**
* Creates a new action that initializes a git repository of the content in the workspace
@@ -76,6 +77,7 @@ export function createGithubRepoPushAction(options: {
id: 'github:repo:push',
description:
'Initializes a git repository of contents in workspace and publishes it to GitHub.',
examples,
schema: {
input: {
type: 'object',