@backstage/plugin-scaffolder-backend 1.15.0-next.1 → 1.15.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ScaffolderEntitiesProcessor-70d9fced.cjs.js","sources":["../../src/scaffolder/actions/builtin/catalog/register.ts","../../src/scaffolder/actions/builtin/catalog/write.ts","../../src/scaffolder/actions/builtin/catalog/fetch.ts","../../src/scaffolder/actions/builtin/debug/log.ts","../../src/scaffolder/actions/builtin/debug/wait.ts","../../src/scaffolder/actions/builtin/fetch/helpers.ts","../../src/scaffolder/actions/builtin/fetch/plain.ts","../../src/scaffolder/actions/builtin/fetch/plainFile.ts","../../src/lib/templating/SecureTemplater.ts","../../src/scaffolder/actions/builtin/publish/util.ts","../../src/lib/templating/filters.ts","../../src/scaffolder/actions/builtin/fetch/template.ts","../../src/scaffolder/actions/builtin/filesystem/delete.ts","../../src/scaffolder/actions/builtin/filesystem/rename.ts","../../src/scaffolder/actions/builtin/helpers.ts","../../src/scaffolder/actions/builtin/github/helpers.ts","../../src/scaffolder/actions/builtin/github/githubActionsDispatch.ts","../../src/scaffolder/actions/builtin/github/githubIssuesLabel.ts","../../src/scaffolder/actions/builtin/github/inputProperties.ts","../../src/scaffolder/actions/builtin/github/outputProperties.ts","../../src/scaffolder/actions/builtin/github/githubRepoCreate.ts","../../src/scaffolder/actions/builtin/github/githubRepoPush.ts","../../src/scaffolder/actions/builtin/github/githubWebhook.ts","../../src/scaffolder/actions/builtin/publish/azure.ts","../../src/scaffolder/actions/builtin/publish/bitbucket.ts","../../src/scaffolder/actions/builtin/publish/bitbucketCloud.ts","../../src/scaffolder/actions/builtin/publish/bitbucketServer.ts","../../src/scaffolder/actions/builtin/publish/gerrit.ts","../../src/scaffolder/actions/builtin/publish/gerritReview.ts","../../src/scaffolder/actions/builtin/publish/github.ts","../../src/lib/files/serializeDirectoryContents.ts","../../src/lib/files/deserializeDirectoryContents.ts","../../src/scaffolder/actions/builtin/publish/githubPullRequest.ts","../../src/scaffolder/actions/builtin/publish/gitlab.ts","../../src/scaffolder/actions/builtin/publish/gitlabMergeRequest.ts","../../src/scaffolder/actions/builtin/createBuiltinActions.ts","../../src/scaffolder/actions/TemplateActionRegistry.ts","../../src/scaffolder/tasks/DatabaseTaskStore.ts","../../src/scaffolder/tasks/StorageTaskBroker.ts","../../src/scaffolder/tasks/helper.ts","../../src/util/metrics.ts","../../src/service/rules.ts","../../src/scaffolder/tasks/NunjucksWorkflowRunner.ts","../../src/scaffolder/tasks/TaskWorker.ts","../../src/scaffolder/dryrun/DecoratedActionsRegistry.ts","../../src/scaffolder/dryrun/createDryRunner.ts","../../src/service/helpers.ts","../../src/service/router.ts","../../src/processor/ScaffolderEntitiesProcessor.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport { stringifyEntityRef, Entity } from '@backstage/catalog-model';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport yaml from 'yaml';\n\nconst id = 'catalog:register';\n\nconst examples = [\n {\n description: 'Register with the catalog',\n example: yaml.stringify({\n steps: [\n {\n action: id,\n id: 'register-with-catalog',\n name: 'Register with the catalog',\n input: {\n catalogInfoUrl:\n 'http://github.com/backstage/backstage/blob/master/catalog-info.yaml',\n },\n },\n ],\n }),\n },\n];\n\n/**\n * Registers entities from a catalog descriptor file in the workspace into the software catalog.\n * @public\n */\nexport function createCatalogRegisterAction(options: {\n catalogClient: CatalogApi;\n integrations: ScmIntegrations;\n}) {\n const { catalogClient, integrations } = options;\n\n return createTemplateAction<\n | { catalogInfoUrl: string; optional?: boolean }\n | { repoContentsUrl: string; catalogInfoPath?: string; optional?: boolean }\n >({\n id,\n description:\n 'Registers entities from a catalog descriptor file in the workspace into the software catalog.',\n examples,\n schema: {\n input: {\n oneOf: [\n {\n type: 'object',\n required: ['catalogInfoUrl'],\n properties: {\n catalogInfoUrl: {\n title: 'Catalog Info URL',\n description:\n 'An absolute URL pointing to the catalog info file location',\n type: 'string',\n },\n optional: {\n title: 'Optional',\n description:\n 'Permit the registered location to optionally exist. Default: false',\n type: 'boolean',\n },\n },\n },\n {\n type: 'object',\n required: ['repoContentsUrl'],\n properties: {\n repoContentsUrl: {\n title: 'Repository Contents URL',\n description:\n 'An absolute URL pointing to the root of a repository directory tree',\n type: 'string',\n },\n catalogInfoPath: {\n title: 'Fetch URL',\n description:\n 'A relative path from the repo root pointing to the catalog info file, defaults to /catalog-info.yaml',\n type: 'string',\n },\n optional: {\n title: 'Optional',\n description:\n 'Permit the registered location to optionally exist. Default: false',\n type: 'boolean',\n },\n },\n },\n ],\n },\n output: {\n type: 'object',\n required: ['catalogInfoUrl'],\n properties: {\n entityRef: {\n type: 'string',\n },\n catalogInfoUrl: {\n type: 'string',\n },\n },\n },\n },\n async handler(ctx) {\n const { input } = ctx;\n\n let catalogInfoUrl;\n if ('catalogInfoUrl' in input) {\n catalogInfoUrl = input.catalogInfoUrl;\n } else {\n const { repoContentsUrl, catalogInfoPath = '/catalog-info.yaml' } =\n input;\n const integration = integrations.byUrl(repoContentsUrl);\n if (!integration) {\n throw new InputError(\n `No integration found for host ${repoContentsUrl}`,\n );\n }\n\n catalogInfoUrl = integration.resolveUrl({\n base: repoContentsUrl,\n url: catalogInfoPath,\n });\n }\n\n ctx.logger.info(`Registering ${catalogInfoUrl} in the catalog`);\n\n try {\n // 1st try to register the location, this will throw an error if the location already exists (see catch)\n await catalogClient.addLocation(\n {\n type: 'url',\n target: catalogInfoUrl,\n },\n ctx.secrets?.backstageToken\n ? { token: ctx.secrets.backstageToken }\n : {},\n );\n } catch (e) {\n if (!input.optional) {\n // if optional is false or unset, it is not allowed to register the same location twice, we rethrow the error\n throw e;\n }\n }\n\n try {\n // 2nd retry the registration as a dry run, this will not throw an error if the location already exists\n const result = await catalogClient.addLocation(\n {\n dryRun: true,\n type: 'url',\n target: catalogInfoUrl,\n },\n ctx.secrets?.backstageToken\n ? { token: ctx.secrets.backstageToken }\n : {},\n );\n\n if (result.entities.length) {\n const { entities } = result;\n let entity: Entity | undefined;\n // prioritise 'Component' type as it is the most central kind of entity\n entity = entities.find(\n e =>\n !e.metadata.name.startsWith('generated-') &&\n e.kind === 'Component',\n );\n if (!entity) {\n entity = entities.find(\n e => !e.metadata.name.startsWith('generated-'),\n );\n }\n if (!entity) {\n entity = entities[0];\n }\n\n ctx.output('entityRef', stringifyEntityRef(entity));\n }\n } catch (e) {\n if (!input.optional) {\n throw e;\n }\n }\n\n ctx.output('catalogInfoUrl', catalogInfoUrl);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport * as yaml from 'yaml';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\nimport { z } from 'zod';\n\nconst id = 'catalog:write';\n\nconst examples = [\n {\n description: 'Write a catalog yaml file',\n example: yaml.stringify({\n steps: [\n {\n action: id,\n id: 'create-catalog-info-file',\n name: 'Create catalog file',\n input: {\n entity: {\n apiVersion: 'backstage.io/v1alpha1',\n kind: 'Component',\n metadata: {\n name: 'test',\n annotations: {},\n },\n spec: {\n type: 'service',\n lifecycle: 'production',\n owner: 'default/owner',\n },\n },\n },\n },\n ],\n }),\n },\n];\n\n/**\n * Writes a catalog descriptor file containing the provided entity to a path in the workspace.\n * @public\n */\n\nexport function createCatalogWriteAction() {\n return createTemplateAction({\n id,\n description: 'Writes the catalog-info.yaml for your template',\n schema: {\n input: z.object({\n filePath: z\n .string()\n .optional()\n .describe('Defaults to catalog-info.yaml'),\n // TODO: this should reference an zod entity validator if it existed.\n entity: z\n .record(z.any())\n .describe(\n 'You can provide the same values used in the Entity schema.',\n ),\n }),\n },\n examples,\n supportsDryRun: true,\n async handler(ctx) {\n ctx.logStream.write(`Writing catalog-info.yaml`);\n const { filePath, entity } = ctx.input;\n const path = filePath ?? 'catalog-info.yaml';\n\n await fs.writeFile(\n resolveSafeChildPath(ctx.workspacePath, path),\n yaml.stringify(entity),\n );\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CatalogApi } from '@backstage/catalog-client';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport yaml from 'yaml';\nimport { z } from 'zod';\nimport { parseEntityRef, stringifyEntityRef } from '@backstage/catalog-model';\n\nconst id = 'catalog:fetch';\n\nconst examples = [\n {\n description: 'Fetch entity by reference',\n example: yaml.stringify({\n steps: [\n {\n action: id,\n id: 'fetch',\n name: 'Fetch catalog entity',\n input: {\n entityRef: 'component:default/name',\n },\n },\n ],\n }),\n },\n {\n description: 'Fetch multiple entities by referencse',\n example: yaml.stringify({\n steps: [\n {\n action: id,\n id: 'fetchMultiple',\n name: 'Fetch catalog entities',\n input: {\n entityRefs: ['component:default/name'],\n },\n },\n ],\n }),\n },\n];\n\n/**\n * Returns entity or entities from the catalog by entity reference(s).\n *\n * @public\n */\nexport function createFetchCatalogEntityAction(options: {\n catalogClient: CatalogApi;\n}) {\n const { catalogClient } = options;\n\n return createTemplateAction({\n id,\n description:\n 'Returns entity or entities from the catalog by entity reference(s)',\n examples,\n supportsDryRun: true,\n schema: {\n input: z.object({\n entityRef: z\n .string({\n description: 'Entity reference of the entity to get',\n })\n .optional(),\n entityRefs: z\n .array(z.string(), {\n description: 'Entity references of the entities to get',\n })\n .optional(),\n optional: z\n .boolean({\n description:\n 'Allow the entity or entities to optionally exist. Default: false',\n })\n .optional(),\n defaultKind: z.string({ description: 'The default kind' }).optional(),\n defaultNamespace: z\n .string({ description: 'The default namespace' })\n .optional(),\n }),\n output: z.object({\n entity: z\n .any({\n description:\n 'Object containing same values used in the Entity schema. Only when used with `entityRef` parameter.',\n })\n .optional(),\n entities: z\n .array(\n z.any({\n description:\n 'Array containing objects with same values used in the Entity schema. Only when used with `entityRefs` parameter.',\n }),\n )\n .optional(),\n }),\n },\n async handler(ctx) {\n const { entityRef, entityRefs, optional, defaultKind, defaultNamespace } =\n ctx.input;\n if (!entityRef && !entityRefs) {\n if (optional) {\n return;\n }\n throw new Error('Missing entity reference or references');\n }\n\n if (entityRef) {\n const entity = await catalogClient.getEntityByRef(\n stringifyEntityRef(\n parseEntityRef(entityRef, { defaultKind, defaultNamespace }),\n ),\n {\n token: ctx.secrets?.backstageToken,\n },\n );\n\n if (!entity && !optional) {\n throw new Error(`Entity ${entityRef} not found`);\n }\n ctx.output('entity', entity ?? null);\n }\n\n if (entityRefs) {\n const entities = await catalogClient.getEntitiesByRefs(\n {\n entityRefs: entityRefs.map(ref =>\n stringifyEntityRef(\n parseEntityRef(ref, { defaultKind, defaultNamespace }),\n ),\n ),\n },\n {\n token: ctx.secrets?.backstageToken,\n },\n );\n\n const finalEntities = entities.items.map((e, i) => {\n if (!e && !optional) {\n throw new Error(`Entity ${entityRefs[i]} not found`);\n }\n return e ?? null;\n });\n\n ctx.output('entities', finalEntities);\n }\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { readdir, stat } from 'fs-extra';\nimport { relative, join } from 'path';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport yaml from 'yaml';\n\nconst id = 'debug:log';\n\nconst examples = [\n {\n description: 'Write a debug message',\n example: yaml.stringify({\n steps: [\n {\n action: id,\n id: 'write-debug-line',\n name: 'Write \"Hello Backstage!\" log line',\n input: {\n message: 'Hello Backstage!',\n },\n },\n ],\n }),\n },\n {\n description: 'List the workspace directory',\n example: yaml.stringify({\n steps: [\n {\n action: id,\n id: 'write-workspace-directory',\n name: 'List the workspace directory',\n input: {\n listWorkspace: true,\n },\n },\n ],\n }),\n },\n];\n\n/**\n * Writes a message into the log or lists all files in the workspace\n *\n * @remarks\n *\n * This task is useful for local development and testing of both the scaffolder\n * and scaffolder templates.\n *\n * @public\n */\nexport function createDebugLogAction() {\n return createTemplateAction<{ message?: string; listWorkspace?: boolean }>({\n id,\n description:\n 'Writes a message into the log or lists all files in the workspace.',\n examples,\n schema: {\n input: {\n type: 'object',\n properties: {\n message: {\n title: 'Message to output.',\n type: 'string',\n },\n listWorkspace: {\n title: 'List all files in the workspace, if true.',\n type: 'boolean',\n },\n extra: {\n title: 'Extra info',\n },\n },\n },\n },\n supportsDryRun: true,\n async handler(ctx) {\n ctx.logger.info(JSON.stringify(ctx.input, null, 2));\n\n if (ctx.input?.message) {\n ctx.logStream.write(ctx.input.message);\n }\n\n if (ctx.input?.listWorkspace) {\n const files = await recursiveReadDir(ctx.workspacePath);\n ctx.logStream.write(\n `Workspace:\\n${files\n .map(f => ` - ${relative(ctx.workspacePath, f)}`)\n .join('\\n')}`,\n );\n }\n },\n });\n}\n\nexport async function recursiveReadDir(dir: string): Promise<string[]> {\n const subdirs = await readdir(dir);\n const files = await Promise.all(\n subdirs.map(async subdir => {\n const res = join(dir, subdir);\n return (await stat(res)).isDirectory() ? recursiveReadDir(res) : [res];\n }),\n );\n return files.reduce((a, f) => a.concat(f), []);\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { HumanDuration } from '@backstage/types';\nimport yaml from 'yaml';\nimport { Duration } from 'luxon';\n\nconst id = 'debug:wait';\n\nconst MAX_WAIT_TIME_IN_ISO = 'T00:00:30';\n\nconst examples = [\n {\n description: 'Waiting for 5 seconds',\n example: yaml.stringify({\n steps: [\n {\n action: id,\n id: 'wait-5sec',\n name: 'Waiting for 5 seconds',\n input: {\n seconds: 5,\n },\n },\n ],\n }),\n },\n {\n description: 'Waiting for 5 minutes',\n example: yaml.stringify({\n steps: [\n {\n action: id,\n id: 'wait-5min',\n name: 'Waiting for 5 minutes',\n input: {\n minutes: 5,\n },\n },\n ],\n }),\n },\n];\n\n/**\n * Waits for a certain period of time.\n *\n * @remarks\n *\n * This task is useful to give some waiting time for manual intervention.\n * Has to be used in a combination with other actions.\n *\n * @public\n */\nexport function createWaitAction(options?: {\n maxWaitTime?: Duration | HumanDuration;\n}) {\n const toDuration = (\n maxWaitTime: Duration | HumanDuration | undefined,\n ): Duration => {\n if (maxWaitTime) {\n if (maxWaitTime instanceof Duration) {\n return maxWaitTime;\n }\n return Duration.fromObject(maxWaitTime);\n }\n return Duration.fromISOTime(MAX_WAIT_TIME_IN_ISO);\n };\n\n return createTemplateAction<HumanDuration>({\n id,\n description: 'Waits for a certain period of time.',\n examples,\n schema: {\n input: {\n type: 'object',\n properties: {\n minutes: {\n title: 'Waiting period in minutes.',\n type: 'number',\n },\n seconds: {\n title: 'Waiting period in seconds.',\n type: 'number',\n },\n milliseconds: {\n title: 'Waiting period in milliseconds.',\n type: 'number',\n },\n },\n },\n },\n async handler(ctx) {\n const delayTime = Duration.fromObject(ctx.input);\n const maxWait = toDuration(options?.maxWaitTime);\n\n if (delayTime.minus(maxWait).toMillis() > 0) {\n throw new Error(\n `Waiting duration is longer than the maximum threshold of ${maxWait.toHuman()}`,\n );\n }\n\n await new Promise(resolve => {\n const controller = new AbortController();\n const timeoutHandle = setTimeout(abort, delayTime.toMillis());\n ctx.signal?.addEventListener('abort', abort);\n\n function abort() {\n ctx.signal?.removeEventListener('abort', abort);\n clearTimeout(timeoutHandle!);\n controller.abort();\n resolve('finished');\n }\n });\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolveSafeChildPath, UrlReader } from '@backstage/backend-common';\nimport { InputError } from '@backstage/errors';\nimport { ScmIntegrations } from '@backstage/integration';\nimport fs from 'fs-extra';\nimport path from 'path';\n\n/**\n * A helper function that reads the contents of a directory from the given URL.\n * Can be used in your own actions, and also used behind fetch:template and fetch:plain\n *\n * @public\n */\nexport async function fetchContents(options: {\n reader: UrlReader;\n integrations: ScmIntegrations;\n baseUrl?: string;\n fetchUrl?: string;\n outputPath: string;\n}) {\n const { reader, integrations, baseUrl, fetchUrl = '.', outputPath } = options;\n\n const fetchUrlIsAbsolute = isFetchUrlAbsolute(fetchUrl);\n\n // We handle both file locations and url ones\n if (!fetchUrlIsAbsolute && baseUrl?.startsWith('file://')) {\n const basePath = baseUrl.slice('file://'.length);\n const srcDir = resolveSafeChildPath(path.dirname(basePath), fetchUrl);\n await fs.copy(srcDir, outputPath);\n } else {\n const readUrl = getReadUrl(fetchUrl, baseUrl, integrations);\n\n const res = await reader.readTree(readUrl);\n await fs.ensureDir(outputPath);\n await res.dir({ targetDir: outputPath });\n }\n}\n\n/**\n * A helper function that reads the content of a single file from the given URL.\n * Can be used in your own actions, and also used behind `fetch:plain:file`\n */\nexport async function fetchFile(options: {\n reader: UrlReader;\n integrations: ScmIntegrations;\n baseUrl?: string;\n fetchUrl?: string;\n outputPath: string;\n}) {\n const { reader, integrations, baseUrl, fetchUrl = '.', outputPath } = options;\n\n const fetchUrlIsAbsolute = isFetchUrlAbsolute(fetchUrl);\n\n // We handle both file locations and url ones\n if (!fetchUrlIsAbsolute && baseUrl?.startsWith('file://')) {\n const basePath = baseUrl.slice('file://'.length);\n const src = resolveSafeChildPath(path.dirname(basePath), fetchUrl);\n await fs.copyFile(src, outputPath);\n } else {\n const readUrl = getReadUrl(fetchUrl, baseUrl, integrations);\n\n const res = await reader.readUrl(readUrl);\n await fs.ensureDir(path.dirname(outputPath));\n const buffer = await res.buffer();\n await fs.outputFile(outputPath, buffer.toString());\n }\n}\n\nfunction isFetchUrlAbsolute(fetchUrl: string) {\n let fetchUrlIsAbsolute = false;\n try {\n // eslint-disable-next-line no-new\n new URL(fetchUrl);\n fetchUrlIsAbsolute = true;\n } catch {\n /* ignored */\n }\n return fetchUrlIsAbsolute;\n}\n\nfunction getReadUrl(\n fetchUrl: string,\n baseUrl: string | undefined,\n integrations: ScmIntegrations,\n) {\n if (isFetchUrlAbsolute(fetchUrl)) {\n return fetchUrl;\n } else if (baseUrl) {\n const integration = integrations.byUrl(baseUrl);\n if (!integration) {\n throw new InputError(`No integration found for location ${baseUrl}`);\n }\n\n return integration.resolveUrl({\n url: fetchUrl,\n base: baseUrl,\n });\n }\n throw new InputError(\n `Failed to fetch, template location could not be determined and the fetch URL is relative, ${fetchUrl}`,\n );\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UrlReader, resolveSafeChildPath } from '@backstage/backend-common';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { fetchContents } from './helpers';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\n\n/**\n * Downloads content and places it in the workspace, or optionally\n * in a subdirectory specified by the 'targetPath' input option.\n * @public\n */\nexport function createFetchPlainAction(options: {\n reader: UrlReader;\n integrations: ScmIntegrations;\n}) {\n const { reader, integrations } = options;\n\n return createTemplateAction<{ url: string; targetPath?: string }>({\n id: 'fetch:plain',\n description:\n 'Downloads content and places it in the workspace, or optionally in a subdirectory specified by the `targetPath` input option.',\n schema: {\n input: {\n type: 'object',\n required: ['url'],\n properties: {\n url: {\n title: 'Fetch URL',\n description:\n 'Relative path or absolute URL pointing to the directory tree to fetch',\n type: 'string',\n },\n targetPath: {\n title: 'Target Path',\n description:\n 'Target path within the working directory to download the contents to.',\n type: 'string',\n },\n },\n },\n },\n supportsDryRun: true,\n async handler(ctx) {\n ctx.logger.info('Fetching plain content from remote URL');\n\n // Finally move the template result into the task workspace\n const targetPath = ctx.input.targetPath ?? './';\n const outputPath = resolveSafeChildPath(ctx.workspacePath, targetPath);\n\n await fetchContents({\n reader,\n integrations,\n baseUrl: ctx.templateInfo?.baseUrl,\n fetchUrl: ctx.input.url,\n outputPath,\n });\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UrlReader, resolveSafeChildPath } from '@backstage/backend-common';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { fetchFile } from './helpers';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\n\n/**\n * Downloads content and places it in the workspace, or optionally\n * in a subdirectory specified by the 'targetPath' input option.\n * @public\n */\nexport function createFetchPlainFileAction(options: {\n reader: UrlReader;\n integrations: ScmIntegrations;\n}) {\n const { reader, integrations } = options;\n\n return createTemplateAction<{ url: string; targetPath: string }>({\n id: 'fetch:plain:file',\n description: 'Downloads single file and places it in the workspace.',\n schema: {\n input: {\n type: 'object',\n required: ['url', 'targetPath'],\n properties: {\n url: {\n title: 'Fetch URL',\n description:\n 'Relative path or absolute URL pointing to the single file to fetch.',\n type: 'string',\n },\n targetPath: {\n title: 'Target Path',\n description:\n 'Target path within the working directory to download the file as.',\n type: 'string',\n },\n },\n },\n },\n supportsDryRun: true,\n async handler(ctx) {\n ctx.logger.info('Fetching plain content from remote URL');\n\n // Finally move the template result into the task workspace\n const outputPath = resolveSafeChildPath(\n ctx.workspacePath,\n ctx.input.targetPath,\n );\n\n await fetchFile({\n reader,\n integrations,\n baseUrl: ctx.templateInfo?.baseUrl,\n fetchUrl: ctx.input.url,\n outputPath,\n });\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VM } from 'vm2';\nimport { resolvePackagePath } from '@backstage/backend-common';\nimport fs from 'fs-extra';\nimport { JsonValue } from '@backstage/types';\n\n// language=JavaScript\nconst mkScript = (nunjucksSource: string) => `\nconst { render, renderCompat } = (() => {\n const module = {};\n const process = { env: {} };\n const require = (pkg) => { if (pkg === 'events') { return function (){}; }};\n\n ${nunjucksSource}\n\n const env = module.exports.configure({\n autoescape: false,\n tags: {\n variableStart: '\\${{',\n variableEnd: '}}',\n },\n });\n\n const compatEnv = module.exports.configure({\n autoescape: false,\n tags: {\n variableStart: '{{',\n variableEnd: '}}',\n },\n });\n compatEnv.addFilter('jsonify', compatEnv.getFilter('dump'));\n\n if (typeof templateFilters !== 'undefined') {\n for (const [filterName, filterFn] of Object.entries(templateFilters)) {\n env.addFilter(filterName, (...args) => JSON.parse(filterFn(...args)));\n }\n }\n\n if (typeof templateGlobals !== 'undefined') {\n for (const [globalName, global] of Object.entries(templateGlobals)) {\n if (typeof global === 'function') {\n env.addGlobal(globalName, (...args) => JSON.parse(global(...args)));\n } else {\n env.addGlobal(globalName, JSON.parse(global));\n }\n }\n }\n\n let uninstallCompat = undefined;\n\n function render(str, values) {\n try {\n if (uninstallCompat) {\n uninstallCompat();\n uninstallCompat = undefined;\n }\n return env.renderString(str, JSON.parse(values));\n } catch (error) {\n // Make sure errors don't leak anything\n throw new Error(String(error.message));\n }\n }\n\n function renderCompat(str, values) {\n try {\n if (!uninstallCompat) {\n uninstallCompat = module.exports.installJinjaCompat();\n }\n return compatEnv.renderString(str, JSON.parse(values));\n } catch (error) {\n // Make sure errors don't leak anything\n throw new Error(String(error.message));\n }\n }\n\n return { render, renderCompat };\n})();\n`;\n\n/** @public */\nexport type TemplateFilter = (...args: JsonValue[]) => JsonValue | undefined;\n\n/** @public */\nexport type TemplateGlobal =\n | ((...args: JsonValue[]) => JsonValue | undefined)\n | JsonValue;\n\nexport interface SecureTemplaterOptions {\n /* Enables jinja compatibility and the \"jsonify\" filter */\n cookiecutterCompat?: boolean;\n /* Extra user-provided nunjucks filters */\n templateFilters?: Record<string, TemplateFilter>;\n /* Extra user-provided nunjucks globals */\n templateGlobals?: Record<string, TemplateGlobal>;\n}\n\nexport type SecureTemplateRenderer = (\n template: string,\n values: unknown,\n) => string;\n\nexport class SecureTemplater {\n static async loadRenderer(options: SecureTemplaterOptions = {}) {\n const { cookiecutterCompat, templateFilters, templateGlobals } = options;\n const sandbox: Record<string, any> = {};\n\n if (templateFilters) {\n sandbox.templateFilters = Object.fromEntries(\n Object.entries(templateFilters)\n .filter(([_, filterFunction]) => !!filterFunction)\n .map(([filterName, filterFunction]) => [\n filterName,\n (...args: JsonValue[]) => JSON.stringify(filterFunction(...args)),\n ]),\n );\n }\n if (templateGlobals) {\n sandbox.templateGlobals = Object.fromEntries(\n Object.entries(templateGlobals)\n .filter(([_, global]) => !!global)\n .map(([globalName, global]) => {\n if (typeof global === 'function') {\n return [\n globalName,\n (...args: JsonValue[]) => JSON.stringify(global(...args)),\n ];\n }\n return [globalName, JSON.stringify(global)];\n }),\n );\n }\n const vm = new VM({ sandbox });\n\n const nunjucksSource = await fs.readFile(\n resolvePackagePath(\n '@backstage/plugin-scaffolder-backend',\n 'assets/nunjucks.js.txt',\n ),\n 'utf-8',\n );\n\n vm.run(mkScript(nunjucksSource));\n\n const render: SecureTemplateRenderer = (template, values) => {\n if (!vm) {\n throw new Error('SecureTemplater has not been initialized');\n }\n vm.setGlobal('templateStr', template);\n vm.setGlobal('templateValues', JSON.stringify(values));\n\n if (cookiecutterCompat) {\n return vm.run(`renderCompat(templateStr, templateValues)`);\n }\n\n return vm.run(`render(templateStr, templateValues)`);\n };\n return render;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport { isChildPath } from '@backstage/backend-common';\nimport { join as joinPath, normalize as normalizePath } from 'path';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\n\nexport const getRepoSourceDirectory = (\n workspacePath: string,\n sourcePath: string | undefined,\n) => {\n if (sourcePath) {\n const safeSuffix = normalizePath(sourcePath).replace(\n /^(\\.\\.(\\/|\\\\|$))+/,\n '',\n );\n const path = joinPath(workspacePath, safeSuffix);\n if (!isChildPath(workspacePath, path)) {\n throw new Error('Invalid source path');\n }\n return path;\n }\n return workspacePath;\n};\nexport type RepoSpec = {\n repo: string;\n host: string;\n owner?: string;\n organization?: string;\n workspace?: string;\n project?: string;\n};\n\nexport const parseRepoUrl = (\n repoUrl: string,\n integrations: ScmIntegrationRegistry,\n): RepoSpec => {\n let parsed;\n try {\n parsed = new URL(`https://${repoUrl}`);\n } catch (error) {\n throw new InputError(\n `Invalid repo URL passed to publisher, got ${repoUrl}, ${error}`,\n );\n }\n const host = parsed.host;\n const owner = parsed.searchParams.get('owner') ?? undefined;\n const organization = parsed.searchParams.get('organization') ?? undefined;\n const workspace = parsed.searchParams.get('workspace') ?? undefined;\n const project = parsed.searchParams.get('project') ?? undefined;\n\n const type = integrations.byHost(host)?.type;\n\n if (!type) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n const repo: string = parsed.searchParams.get('repo')!;\n switch (type) {\n case 'bitbucket': {\n if (host === 'www.bitbucket.org') {\n checkRequiredParams(parsed, 'workspace');\n }\n checkRequiredParams(parsed, 'project', 'repo');\n break;\n }\n case 'gitlab': {\n // project is the projectID, and if defined, owner and repo won't be needed.\n if (!project) {\n checkRequiredParams(parsed, 'owner', 'repo');\n }\n break;\n }\n case 'gerrit': {\n checkRequiredParams(parsed, 'repo');\n break;\n }\n default: {\n checkRequiredParams(parsed, 'repo', 'owner');\n break;\n }\n }\n\n return { host, owner, repo, organization, workspace, project };\n};\nexport const isExecutable = (fileMode: number) => {\n const executeBitMask = 0o000111;\n const res = fileMode & executeBitMask;\n return res > 0;\n};\n\n/**\n * This function checks if the required parameters (given as the `params` argument) are present in the URL\n *\n * @param repoUrl - the URL for the repository\n * @param params - a variadic list of URL query parameter names\n *\n * @throws\n * An InputError exception is thrown if any of the required parameters is not in the URL.\n *\n * @public\n */\nfunction checkRequiredParams(repoUrl: URL, ...params: string[]) {\n for (let i = 0; i < params.length; i++) {\n if (!repoUrl.searchParams.get(params[i])) {\n throw new InputError(\n `Invalid repo URL passed to publisher: ${repoUrl.toString()}, missing ${\n params[i]\n }`,\n );\n }\n }\n}\n","/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { parseEntityRef } from '@backstage/catalog-model';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { JsonValue } from '@backstage/types';\nimport { TemplateFilter } from '..';\nimport { parseRepoUrl } from '../../scaffolder/actions/builtin/publish/util';\nimport get from 'lodash/get';\n\nexport const createDefaultFilters = ({\n integrations,\n}: {\n integrations: ScmIntegrations;\n}): Record<string, TemplateFilter> => {\n return {\n parseRepoUrl: url => parseRepoUrl(url as string, integrations),\n parseEntityRef: ref => parseEntityRef(ref as string),\n pick: (obj: JsonValue, key: JsonValue) => get(obj, key as string),\n projectSlug: repoUrl => {\n const { owner, repo } = parseRepoUrl(repoUrl as string, integrations);\n return `${owner}/${repo}`;\n },\n };\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extname } from 'path';\nimport { resolveSafeChildPath, UrlReader } from '@backstage/backend-common';\nimport { InputError } from '@backstage/errors';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { fetchContents } from './helpers';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport globby from 'globby';\nimport fs from 'fs-extra';\nimport { isBinaryFile } from 'isbinaryfile';\nimport {\n TemplateFilter,\n SecureTemplater,\n TemplateGlobal,\n} from '../../../../lib/templating/SecureTemplater';\nimport { createDefaultFilters } from '../../../../lib/templating/filters';\n\n/**\n * Downloads a skeleton, templates variables into file and directory names and content.\n * Then places the result in the workspace, or optionally in a subdirectory\n * specified by the 'targetPath' input option.\n *\n * @public\n */\nexport function createFetchTemplateAction(options: {\n reader: UrlReader;\n integrations: ScmIntegrations;\n additionalTemplateFilters?: Record<string, TemplateFilter>;\n additionalTemplateGlobals?: Record<string, TemplateGlobal>;\n}) {\n const {\n reader,\n integrations,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n } = options;\n\n const defaultTemplateFilters = createDefaultFilters({ integrations });\n\n return createTemplateAction<{\n url: string;\n targetPath?: string;\n values: any;\n templateFileExtension?: string | boolean;\n\n // Cookiecutter compat options\n /**\n * @deprecated This field is deprecated in favor of copyWithoutTemplating.\n */\n copyWithoutRender?: string[];\n copyWithoutTemplating?: string[];\n cookiecutterCompat?: boolean;\n replace?: boolean;\n }>({\n id: 'fetch:template',\n description:\n 'Downloads a skeleton, templates variables into file and directory names and content, and places the result in the workspace, or optionally in a subdirectory specified by the `targetPath` input option.',\n schema: {\n input: {\n type: 'object',\n required: ['url'],\n properties: {\n url: {\n title: 'Fetch URL',\n description:\n 'Relative path or absolute URL pointing to the directory tree to fetch',\n type: 'string',\n },\n targetPath: {\n title: 'Target Path',\n description:\n 'Target path within the working directory to download the contents to. Defaults to the working directory root.',\n type: 'string',\n },\n values: {\n title: 'Template Values',\n description: 'Values to pass on to the templating engine',\n type: 'object',\n },\n copyWithoutRender: {\n title: '[Deprecated] Copy Without Render',\n description:\n 'An array of glob patterns. Any files or directories which match are copied without being processed as templates.',\n type: 'array',\n items: {\n type: 'string',\n },\n },\n copyWithoutTemplating: {\n title: 'Copy Without Templating',\n description:\n 'An array of glob patterns. Contents of matched files or directories are copied without being processed, but paths are subject to rendering.',\n type: 'array',\n items: {\n type: 'string',\n },\n },\n cookiecutterCompat: {\n title: 'Cookiecutter compatibility mode',\n description:\n 'Enable features to maximise compatibility with templates built for fetch:cookiecutter',\n type: 'boolean',\n },\n templateFileExtension: {\n title: 'Template File Extension',\n description:\n 'If set, only files with the given extension will be templated. If set to `true`, the default extension `.njk` is used.',\n type: ['string', 'boolean'],\n },\n replace: {\n title: 'Replace files',\n description:\n 'If set, replace files in targetPath instead of skipping existing ones.',\n type: 'boolean',\n },\n },\n },\n },\n supportsDryRun: true,\n async handler(ctx) {\n ctx.logger.info('Fetching template content from remote URL');\n\n const workDir = await ctx.createTemporaryDirectory();\n const templateDir = resolveSafeChildPath(workDir, 'template');\n\n const targetPath = ctx.input.targetPath ?? './';\n const outputDir = resolveSafeChildPath(ctx.workspacePath, targetPath);\n if (ctx.input.copyWithoutRender && ctx.input.copyWithoutTemplating) {\n throw new InputError(\n 'Fetch action input copyWithoutRender and copyWithoutTemplating can not be used at the same time',\n );\n }\n\n let copyOnlyPatterns: string[] | undefined;\n let renderFilename: boolean;\n if (ctx.input.copyWithoutRender) {\n ctx.logger.warn(\n '[Deprecated] Please use copyWithoutTemplating instead.',\n );\n copyOnlyPatterns = ctx.input.copyWithoutRender;\n renderFilename = false;\n } else {\n copyOnlyPatterns = ctx.input.copyWithoutTemplating;\n renderFilename = true;\n }\n\n if (copyOnlyPatterns && !Array.isArray(copyOnlyPatterns)) {\n throw new InputError(\n 'Fetch action input copyWithoutRender/copyWithoutTemplating must be an Array',\n );\n }\n\n if (\n ctx.input.templateFileExtension &&\n (copyOnlyPatterns || ctx.input.cookiecutterCompat)\n ) {\n throw new InputError(\n 'Fetch action input extension incompatible with copyWithoutRender/copyWithoutTemplating and cookiecutterCompat',\n );\n }\n\n let extension: string | false = false;\n if (ctx.input.templateFileExtension) {\n extension =\n ctx.input.templateFileExtension === true\n ? '.njk'\n : ctx.input.templateFileExtension;\n if (!extension.startsWith('.')) {\n extension = `.${extension}`;\n }\n }\n\n await fetchContents({\n reader,\n integrations,\n baseUrl: ctx.templateInfo?.baseUrl,\n fetchUrl: ctx.input.url,\n outputPath: templateDir,\n });\n\n ctx.logger.info('Listing files and directories in template');\n const allEntriesInTemplate = await globby(`**/*`, {\n cwd: templateDir,\n dot: true,\n onlyFiles: false,\n markDirectories: true,\n followSymbolicLinks: false,\n });\n\n const nonTemplatedEntries = new Set(\n (\n await Promise.all(\n (copyOnlyPatterns || []).map(pattern =>\n globby(pattern, {\n cwd: templateDir,\n dot: true,\n onlyFiles: false,\n markDirectories: true,\n followSymbolicLinks: false,\n }),\n ),\n )\n ).flat(),\n );\n\n // Cookiecutter prefixes all parameters in templates with\n // `cookiecutter.`. To replicate this, we wrap our parameters\n // in an object with a `cookiecutter` property when compat\n // mode is enabled.\n const { cookiecutterCompat, values } = ctx.input;\n const context = {\n [cookiecutterCompat ? 'cookiecutter' : 'values']: values,\n };\n\n ctx.logger.info(\n `Processing ${allEntriesInTemplate.length} template files/directories with input values`,\n ctx.input.values,\n );\n\n const renderTemplate = await SecureTemplater.loadRenderer({\n cookiecutterCompat: ctx.input.cookiecutterCompat,\n templateFilters: {\n ...defaultTemplateFilters,\n ...additionalTemplateFilters,\n },\n templateGlobals: additionalTemplateGlobals,\n });\n\n for (const location of allEntriesInTemplate) {\n let renderContents: boolean;\n\n let localOutputPath = location;\n if (extension) {\n renderContents = extname(localOutputPath) === extension;\n if (renderContents) {\n localOutputPath = localOutputPath.slice(0, -extension.length);\n }\n // extension is mutual exclusive with copyWithoutRender/copyWithoutTemplating,\n // therefore the output path is always rendered.\n localOutputPath = renderTemplate(localOutputPath, context);\n } else {\n renderContents = !nonTemplatedEntries.has(location);\n // The logic here is a bit tangled because it depends on two variables.\n // If renderFilename is true, which means copyWithoutTemplating is used,\n // then the path is always rendered.\n // If renderFilename is false, which means copyWithoutRender is used,\n // then matched file/directory won't be processed, same as before.\n if (renderFilename) {\n localOutputPath = renderTemplate(localOutputPath, context);\n } else {\n localOutputPath = renderContents\n ? renderTemplate(localOutputPath, context)\n : localOutputPath;\n }\n }\n\n if (containsSkippedContent(localOutputPath)) {\n continue;\n }\n\n const outputPath = resolveSafeChildPath(outputDir, localOutputPath);\n if (fs.existsSync(outputPath) && !ctx.input.replace) {\n continue;\n }\n\n if (!renderContents && !extension) {\n ctx.logger.info(\n `Copying file/directory ${location} without processing.`,\n );\n }\n\n if (location.endsWith('/')) {\n ctx.logger.info(\n `Writing directory ${location} to template output path.`,\n );\n await fs.ensureDir(outputPath);\n } else {\n const inputFilePath = resolveSafeChildPath(templateDir, location);\n const stats = await fs.promises.lstat(inputFilePath);\n\n if (stats.isSymbolicLink() || (await isBinaryFile(inputFilePath))) {\n ctx.logger.info(\n `Copying file binary or symbolic link at ${location}, to template output path.`,\n );\n await fs.copy(inputFilePath, outputPath);\n } else {\n const statsObj = await fs.stat(inputFilePath);\n ctx.logger.info(\n `Writing file ${location} to template output path with mode ${statsObj.mode}.`,\n );\n const inputFileContents = await fs.readFile(inputFilePath, 'utf-8');\n await fs.outputFile(\n outputPath,\n renderContents\n ? renderTemplate(inputFileContents, context)\n : inputFileContents,\n { mode: statsObj.mode },\n );\n }\n }\n }\n\n ctx.logger.info(`Template result written to ${outputDir}`);\n },\n });\n}\n\nfunction containsSkippedContent(localOutputPath: string): boolean {\n // if the path is empty means that there is a file skipped in the root\n // if the path starts with a separator it means that the root directory has been skipped\n // if the path includes // means that there is a subdirectory skipped\n // All paths returned are considered with / separator because of globby returning the linux separator for all os'.\n return (\n localOutputPath === '' ||\n localOutputPath.startsWith('/') ||\n localOutputPath.includes('//')\n );\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { InputError } from '@backstage/errors';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\nimport fs from 'fs-extra';\n\n/**\n * Creates new action that enables deletion of files and directories in the workspace.\n * @public\n */\nexport const createFilesystemDeleteAction = () => {\n return createTemplateAction<{ files: string[] }>({\n id: 'fs:delete',\n description: 'Deletes files and directories from the workspace',\n schema: {\n input: {\n required: ['files'],\n type: 'object',\n properties: {\n files: {\n title: 'Files',\n description: 'A list of files and directories that will be deleted',\n type: 'array',\n items: {\n type: 'string',\n },\n },\n },\n },\n },\n supportsDryRun: true,\n async handler(ctx) {\n if (!Array.isArray(ctx.input?.files)) {\n throw new InputError('files must be an Array');\n }\n\n for (const file of ctx.input.files) {\n const filepath = resolveSafeChildPath(ctx.workspacePath, file);\n\n try {\n await fs.remove(filepath);\n ctx.logger.info(`File ${filepath} deleted successfully`);\n } catch (err) {\n ctx.logger.error(`Failed to delete file ${filepath}:`, err);\n throw err;\n }\n }\n },\n });\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\nimport { InputError } from '@backstage/errors';\nimport fs from 'fs-extra';\n\n/**\n * Creates a new action that allows renames of files and directories in the workspace.\n * @public\n */\nexport const createFilesystemRenameAction = () => {\n return createTemplateAction<{\n files: Array<{\n from: string;\n to: string;\n overwrite?: boolean;\n }>;\n }>({\n id: 'fs:rename',\n description: 'Renames files and directories within the workspace',\n schema: {\n input: {\n required: ['files'],\n type: 'object',\n properties: {\n files: {\n title: 'Files',\n description:\n 'A list of file and directory names that will be renamed',\n type: 'array',\n items: {\n type: 'object',\n required: ['from', 'to'],\n properties: {\n from: {\n type: 'string',\n title: 'The source location of the file to be renamed',\n },\n to: {\n type: 'string',\n title: 'The destination of the new file',\n },\n overwrite: {\n type: 'boolean',\n title:\n 'Overwrite existing file or directory, default is false',\n },\n },\n },\n },\n },\n },\n },\n supportsDryRun: true,\n async handler(ctx) {\n if (!Array.isArray(ctx.input?.files)) {\n throw new InputError('files must be an Array');\n }\n\n for (const file of ctx.input.files) {\n if (!file.from || !file.to) {\n throw new InputError('each file must have a from and to property');\n }\n\n const sourceFilepath = resolveSafeChildPath(\n ctx.workspacePath,\n file.from,\n );\n const destFilepath = resolveSafeChildPath(ctx.workspacePath, file.to);\n\n try {\n await fs.move(sourceFilepath, destFilepath, {\n overwrite: file.overwrite ?? false,\n });\n ctx.logger.info(\n `File ${sourceFilepath} renamed to ${destFilepath} successfully`,\n );\n } catch (err) {\n ctx.logger.error(\n `Failed to rename file ${sourceFilepath} to ${destFilepath}:`,\n err,\n );\n throw err;\n }\n }\n },\n });\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Git } from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport { assertError } from '@backstage/errors';\nimport { spawn, SpawnOptionsWithoutStdio } from 'child_process';\nimport { Octokit } from 'octokit';\nimport { PassThrough, Writable } from 'stream';\nimport { Logger } from 'winston';\n\n/** @public */\nexport type RunCommandOptions = {\n /** command to run */\n command: string;\n /** arguments to pass the command */\n args: string[];\n /** options to pass to spawn */\n options?: SpawnOptionsWithoutStdio;\n /** stream to capture stdout and stderr output */\n logStream?: Writable;\n};\n\n/**\n * Run a command in a sub-process, normally a shell command.\n *\n * @public\n */\nexport const executeShellCommand = async (options: RunCommandOptions) => {\n const {\n command,\n args,\n options: spawnOptions,\n logStream = new PassThrough(),\n } = options;\n await new Promise<void>((resolve, reject) => {\n const process = spawn(command, args, spawnOptions);\n\n process.stdout.on('data', stream => {\n logStream.write(stream);\n });\n\n process.stderr.on('data', stream => {\n logStream.write(stream);\n });\n\n process.on('error', error => {\n return reject(error);\n });\n\n process.on('close', code => {\n if (code !== 0) {\n return reject(\n new Error(`Command ${command} failed, exit code: ${code}`),\n );\n }\n return resolve();\n });\n });\n};\n\nexport async function initRepoAndPush({\n dir,\n remoteUrl,\n auth,\n logger,\n defaultBranch = 'master',\n commitMessage = 'Initial commit',\n gitAuthorInfo,\n}: {\n dir: string;\n remoteUrl: string;\n // For use cases where token has to be used with Basic Auth\n // it has to be provided as password together with a username\n // which may be a fixed value defined by the provider.\n auth: { username: string; password: string } | { token: string };\n logger: Logger;\n defaultBranch?: string;\n commitMessage?: string;\n gitAuthorInfo?: { name?: string; email?: string };\n}): Promise<{ commitHash: string }> {\n const git = Git.fromAuth({\n ...auth,\n logger,\n });\n\n await git.init({\n dir,\n defaultBranch,\n });\n\n await git.add({ dir, filepath: '.' });\n\n // use provided info if possible, otherwise use fallbacks\n const authorInfo = {\n name: gitAuthorInfo?.name ?? 'Scaffolder',\n email: gitAuthorInfo?.email ?? 'scaffolder@backstage.io',\n };\n\n const commitHash = await git.commit({\n dir,\n message: commitMessage,\n author: authorInfo,\n committer: authorInfo,\n });\n await git.addRemote({\n dir,\n url: remoteUrl,\n remote: 'origin',\n });\n\n await git.push({\n dir,\n remote: 'origin',\n });\n\n return { commitHash };\n}\n\nexport async function commitAndPushRepo({\n dir,\n auth,\n logger,\n commitMessage,\n gitAuthorInfo,\n branch = 'master',\n remoteRef,\n}: {\n dir: string;\n // For use cases where token has to be used with Basic Auth\n // it has to be provided as password together with a username\n // which may be a fixed value defined by the provider.\n auth: { username: string; password: string } | { token: string };\n logger: Logger;\n commitMessage: string;\n gitAuthorInfo?: { name?: string; email?: string };\n branch?: string;\n remoteRef?: string;\n}): Promise<{ commitHash: string }> {\n const git = Git.fromAuth({\n ...auth,\n logger,\n });\n\n await git.fetch({ dir });\n await git.checkout({ dir, ref: branch });\n await git.add({ dir, filepath: '.' });\n\n // use provided info if possible, otherwise use fallbacks\n const authorInfo = {\n name: gitAuthorInfo?.name ?? 'Scaffolder',\n email: gitAuthorInfo?.email ?? 'scaffolder@backstage.io',\n };\n\n const commitHash = await git.commit({\n dir,\n message: commitMessage,\n author: authorInfo,\n committer: authorInfo,\n });\n\n await git.push({\n dir,\n remote: 'origin',\n remoteRef: remoteRef ?? `refs/heads/${branch}`,\n });\n\n return { commitHash };\n}\n\ntype BranchProtectionOptions = {\n client: Octokit;\n owner: string;\n repoName: string;\n logger: Logger;\n requireCodeOwnerReviews: boolean;\n requiredStatusCheckContexts?: string[];\n bypassPullRequestAllowances?: {\n users?: string[];\n teams?: string[];\n apps?: string[];\n };\n requiredApprovingReviewCount?: number;\n restrictions?: {\n users: string[];\n teams: string[];\n apps?: string[];\n };\n requireBranchesToBeUpToDate?: boolean;\n requiredConversationResolution?: boolean;\n defaultBranch?: string;\n enforceAdmins?: boolean;\n dismissStaleReviews?: boolean;\n requiredCommitSigning?: boolean;\n};\n\nexport const enableBranchProtectionOnDefaultRepoBranch = async ({\n repoName,\n client,\n owner,\n logger,\n requireCodeOwnerReviews,\n bypassPullRequestAllowances,\n requiredApprovingReviewCount,\n restrictions,\n requiredStatusCheckContexts = [],\n requireBranchesToBeUpToDate = true,\n requiredConversationResolution = false,\n defaultBranch = 'master',\n enforceAdmins = true,\n dismissStaleReviews = false,\n requiredCommitSigning = false,\n}: BranchProtectionOptions): Promise<void> => {\n const tryOnce = async () => {\n try {\n await client.rest.repos.updateBranchProtection({\n mediaType: {\n /**\n * 👇 we need this preview because allowing a custom\n * reviewer count on branch protection is a preview\n * feature\n *\n * More here: https://docs.github.com/en/rest/overview/api-previews#require-multiple-approving-reviews\n */\n previews: ['luke-cage-preview'],\n },\n owner,\n repo: repoName,\n branch: defaultBranch,\n required_status_checks: {\n strict: requireBranchesToBeUpToDate,\n contexts: requiredStatusCheckContexts,\n },\n restrictions: restrictions ?? null,\n enforce_admins: enforceAdmins,\n required_pull_request_reviews: {\n required_approving_review_count: requiredApprovingReviewCount,\n require_code_owner_reviews: requireCodeOwnerReviews,\n bypass_pull_request_allowances: bypassPullRequestAllowances,\n dismiss_stale_reviews: dismissStaleReviews,\n },\n required_conversation_resolution: requiredConversationResolution,\n });\n\n if (requiredCommitSigning) {\n await client.rest.repos.createCommitSignatureProtection({\n owner,\n repo: repoName,\n branch: defaultBranch,\n });\n }\n } catch (e) {\n assertError(e);\n if (\n e.message.includes(\n 'Upgrade to GitHub Pro or make this repository public to enable this feature',\n )\n ) {\n logger.warn(\n 'Branch protection was not enabled as it requires GitHub Pro for private repositories',\n );\n } else {\n throw e;\n }\n }\n };\n\n try {\n await tryOnce();\n } catch (e) {\n if (!e.message.includes('Branch not found')) {\n throw e;\n }\n\n // GitHub has eventual consistency. Fail silently, wait, and try again.\n await new Promise(resolve => setTimeout(resolve, 600));\n await tryOnce();\n }\n};\n\nexport function getGitCommitMessage(\n gitCommitMessage: string | undefined,\n config: Config,\n): string | undefined {\n return gitCommitMessage\n ? gitCommitMessage\n : config.getOptionalString('scaffolder.defaultCommitMessage');\n}\n\nexport function entityRefToName(name: string): string {\n return name.replace(/^.*[:/]/g, '');\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { assertError, InputError, NotFoundError } from '@backstage/errors';\nimport {\n DefaultGithubCredentialsProvider,\n GithubCredentialsProvider,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { OctokitOptions } from '@octokit/core/dist-types/types';\nimport { Octokit } from 'octokit';\nimport { Logger } from 'winston';\nimport {\n enableBranchProtectionOnDefaultRepoBranch,\n initRepoAndPush,\n} from '../helpers';\nimport { getRepoSourceDirectory, parseRepoUrl } from '../publish/util';\nimport { entityRefToName } from '../../builtin/helpers';\nimport Sodium from 'libsodium-wrappers';\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\nexport async function getOctokitOptions(options: {\n integrations: ScmIntegrationRegistry;\n credentialsProvider?: GithubCredentialsProvider;\n token?: string;\n repoUrl: string;\n}): Promise<OctokitOptions> {\n const { integrations, credentialsProvider, repoUrl, token } = options;\n const { owner, repo, host } = parseRepoUrl(repoUrl, integrations);\n\n const requestOptions = {\n // set timeout to 60 seconds\n timeout: DEFAULT_TIMEOUT_MS,\n };\n\n if (!owner) {\n throw new InputError(`No owner provided for repo ${repoUrl}`);\n }\n\n const integrationConfig = integrations.github.byHost(host)?.config;\n\n if (!integrationConfig) {\n throw new InputError(`No integration for host ${host}`);\n }\n\n // short circuit the `githubCredentialsProvider` if there is a token provided by the caller already\n if (token) {\n return {\n auth: token,\n baseUrl: integrationConfig.apiBaseUrl,\n previews: ['nebula-preview'],\n request: requestOptions,\n };\n }\n\n const githubCredentialsProvider =\n credentialsProvider ??\n DefaultGithubCredentialsProvider.fromIntegrations(integrations);\n\n // TODO(blam): Consider changing this API to take host and repo instead of repoUrl, as we end up parsing in this function\n // and then parsing in the `getCredentials` function too the other side\n const { token: credentialProviderToken } =\n await githubCredentialsProvider.getCredentials({\n url: `https://${host}/${encodeURIComponent(owner)}/${encodeURIComponent(\n repo,\n )}`,\n });\n\n if (!credentialProviderToken) {\n throw new InputError(\n `No token available for host: ${host}, with owner ${owner}, and repo ${repo}`,\n );\n }\n\n return {\n auth: credentialProviderToken,\n baseUrl: integrationConfig.apiBaseUrl,\n previews: ['nebula-preview'],\n };\n}\n\nexport async function createGithubRepoWithCollaboratorsAndTopics(\n client: Octokit,\n repo: string,\n owner: string,\n repoVisibility: 'private' | 'internal' | 'public',\n description: string | undefined,\n homepage: string | undefined,\n deleteBranchOnMerge: boolean,\n allowMergeCommit: boolean,\n allowSquashMerge: boolean,\n squashMergeCommitTitle: 'PR_TITLE' | 'COMMIT_OR_PR_TITLE' | undefined,\n squashMergeCommitMessage: 'PR_BODY' | 'COMMIT_MESSAGES' | 'BLANK' | undefined,\n allowRebaseMerge: boolean,\n allowAutoMerge: boolean,\n access: string | undefined,\n collaborators:\n | (\n | {\n user: string;\n access: string;\n }\n | {\n team: string;\n access: string;\n }\n | {\n /** @deprecated This field is deprecated in favor of team */\n username: string;\n access: 'pull' | 'push' | 'admin' | 'maintain' | 'triage';\n }\n )[]\n | undefined,\n hasProjects: boolean | undefined,\n hasWiki: boolean | undefined,\n hasIssues: boolean | undefined,\n topics: string[] | undefined,\n repoVariables: { [key: string]: string } | undefined,\n secrets: { [key: string]: string } | undefined,\n logger: Logger,\n) {\n // eslint-disable-next-line testing-library/no-await-sync-query\n const user = await client.rest.users.getByUsername({\n username: owner,\n });\n\n if (access?.startsWith(`${owner}/`)) {\n await validateAccessTeam(client, access);\n }\n\n const repoCreationPromise =\n user.data.type === 'Organization'\n ? client.rest.repos.createInOrg({\n name: repo,\n org: owner,\n private: repoVisibility === 'private',\n // @ts-ignore\n visibility: repoVisibility,\n description: description,\n delete_branch_on_merge: deleteBranchOnMerge,\n allow_merge_commit: allowMergeCommit,\n allow_squash_merge: allowSquashMerge,\n squash_merge_commit_title: squashMergeCommitTitle,\n squash_merge_commit_message: squashMergeCommitMessage,\n allow_rebase_merge: allowRebaseMerge,\n allow_auto_merge: allowAutoMerge,\n homepage: homepage,\n has_projects: hasProjects,\n has_wiki: hasWiki,\n has_issues: hasIssues,\n })\n : client.rest.repos.createForAuthenticatedUser({\n name: repo,\n private: repoVisibility === 'private',\n description: description,\n delete_branch_on_merge: deleteBranchOnMerge,\n allow_merge_commit: allowMergeCommit,\n allow_squash_merge: allowSquashMerge,\n squash_merge_commit_title: squashMergeCommitTitle,\n squash_merge_commit_message: squashMergeCommitMessage,\n allow_rebase_merge: allowRebaseMerge,\n allow_auto_merge: allowAutoMerge,\n homepage: homepage,\n has_projects: hasProjects,\n has_wiki: hasWiki,\n has_issues: hasIssues,\n });\n\n let newRepo;\n\n try {\n newRepo = (await repoCreationPromise).data;\n } catch (e) {\n assertError(e);\n if (e.message === 'Resource not accessible by integration') {\n logger.warn(\n `The GitHub app or token provided may not have the required permissions to create the ${user.data.type} repository ${owner}/${repo}.`,\n );\n }\n throw new Error(\n `Failed to create the ${user.data.type} repository ${owner}/${repo}, ${e.message}`,\n );\n }\n\n if (access?.startsWith(`${owner}/`)) {\n const [, team] = access.split('/');\n await client.rest.teams.addOrUpdateRepoPermissionsInOrg({\n org: owner,\n team_slug: team,\n owner,\n repo,\n permission: 'admin',\n });\n // No need to add access if it's the person who owns the personal account\n } else if (access && access !== owner) {\n await client.rest.repos.addCollaborator({\n owner,\n repo,\n username: access,\n permission: 'admin',\n });\n }\n\n if (collaborators) {\n for (const collaborator of collaborators) {\n try {\n if ('user' in collaborator) {\n await client.rest.repos.addCollaborator({\n owner,\n repo,\n username: entityRefToName(collaborator.user),\n permission: collaborator.access,\n });\n } else if ('team' in collaborator) {\n await client.rest.teams.addOrUpdateRepoPermissionsInOrg({\n org: owner,\n team_slug: entityRefToName(collaborator.team),\n owner,\n repo,\n permission: collaborator.access,\n });\n }\n } catch (e) {\n assertError(e);\n const name = extractCollaboratorName(collaborator);\n logger.warn(\n `Skipping ${collaborator.access} access for ${name}, ${e.message}`,\n );\n }\n }\n }\n\n if (topics) {\n try {\n await client.rest.repos.replaceAllTopics({\n owner,\n repo,\n names: topics.map(t => t.toLowerCase()),\n });\n } catch (e) {\n assertError(e);\n logger.warn(`Skipping topics ${topics.join(' ')}, ${e.message}`);\n }\n }\n\n for (const [key, value] of Object.entries(repoVariables ?? {})) {\n await client.rest.actions.createRepoVariable({\n owner,\n repo,\n name: key,\n value: value,\n });\n }\n\n if (secrets) {\n const publicKeyResponse = await client.rest.actions.getRepoPublicKey({\n owner,\n repo,\n });\n\n await Sodium.ready;\n const binaryKey = Sodium.from_base64(\n publicKeyResponse.data.key,\n Sodium.base64_variants.ORIGINAL,\n );\n for (const [key, value] of Object.entries(secrets)) {\n const binarySecret = Sodium.from_string(value);\n const encryptedBinarySecret = Sodium.crypto_box_seal(\n binarySecret,\n binaryKey,\n );\n const encryptedBase64Secret = Sodium.to_base64(\n encryptedBinarySecret,\n Sodium.base64_variants.ORIGINAL,\n );\n\n await client.rest.actions.createOrUpdateRepoSecret({\n owner,\n repo,\n secret_name: key,\n encrypted_value: encryptedBase64Secret,\n key_id: publicKeyResponse.data.key_id,\n });\n }\n }\n\n return newRepo;\n}\n\nexport async function initRepoPushAndProtect(\n remoteUrl: string,\n password: string,\n workspacePath: string,\n sourcePath: string | undefined,\n defaultBranch: string,\n protectDefaultBranch: boolean,\n protectEnforceAdmins: boolean,\n owner: string,\n client: Octokit,\n repo: string,\n requireCodeOwnerReviews: boolean,\n bypassPullRequestAllowances:\n | {\n users?: string[];\n teams?: string[];\n apps?: string[];\n }\n | undefined,\n requiredApprovingReviewCount: number,\n restrictions:\n | {\n users: string[];\n teams: string[];\n apps?: string[];\n }\n | undefined,\n requiredStatusCheckContexts: string[],\n requireBranchesToBeUpToDate: boolean,\n requiredConversationResolution: boolean,\n config: Config,\n logger: any,\n gitCommitMessage?: string,\n gitAuthorName?: string,\n gitAuthorEmail?: string,\n dismissStaleReviews?: boolean,\n requiredCommitSigning?: boolean,\n): Promise<{ commitHash: string }> {\n const gitAuthorInfo = {\n name: gitAuthorName\n ? gitAuthorName\n : config.getOptionalString('scaffolder.defaultAuthor.name'),\n email: gitAuthorEmail\n ? gitAuthorEmail\n : config.getOptionalString('scaffolder.defaultAuthor.email'),\n };\n\n const commitMessage = gitCommitMessage\n ? gitCommitMessage\n : config.getOptionalString('scaffolder.defaultCommitMessage');\n\n const commitResult = await initRepoAndPush({\n dir: getRepoSourceDirectory(workspacePath, sourcePath),\n remoteUrl,\n defaultBranch,\n auth: {\n username: 'x-access-token',\n password,\n },\n logger,\n commitMessage,\n gitAuthorInfo,\n });\n\n if (protectDefaultBranch) {\n try {\n await enableBranchProtectionOnDefaultRepoBranch({\n owner,\n client,\n repoName: repo,\n logger,\n defaultBranch,\n bypassPullRequestAllowances,\n requiredApprovingReviewCount,\n restrictions,\n requireCodeOwnerReviews,\n requiredStatusCheckContexts,\n requireBranchesToBeUpToDate,\n requiredConversationResolution,\n enforceAdmins: protectEnforceAdmins,\n dismissStaleReviews: dismissStaleReviews,\n requiredCommitSigning: requiredCommitSigning,\n });\n } catch (e) {\n assertError(e);\n logger.warn(\n `Skipping: default branch protection on '${repo}', ${e.message}`,\n );\n }\n }\n\n return { commitHash: commitResult.commitHash };\n}\n\nfunction extractCollaboratorName(\n collaborator: { user: string } | { team: string } | { username: string },\n) {\n if ('username' in collaborator) return collaborator.username;\n if ('user' in collaborator) return collaborator.user;\n return collaborator.team;\n}\n\nasync function validateAccessTeam(client: Octokit, access: string) {\n const [org, team_slug] = access.split('/');\n try {\n // Below rule disabled because of a 'getByName' check for a different library\n // incorrectly triggers here.\n // eslint-disable-next-line testing-library/no-await-sync-query\n await client.rest.teams.getByName({\n org,\n team_slug,\n });\n } catch (e) {\n if (e.response.data.message === 'Not Found') {\n const message = `Received 'Not Found' from the API; one of org:\n ${org} or team: ${team_slug} was not found within GitHub.`;\n throw new NotFoundError(message);\n }\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport {\n GithubCredentialsProvider,\n ScmIntegrations,\n} from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { Octokit } from 'octokit';\nimport { parseRepoUrl } from '../publish/util';\nimport { getOctokitOptions } from './helpers';\n\n/**\n * Creates a new action that dispatches a GitHub Action workflow for a given branch or tag.\n * @public\n */\nexport function createGithubActionsDispatchAction(options: {\n integrations: ScmIntegrations;\n githubCredentialsProvider?: GithubCredentialsProvider;\n}) {\n const { integrations, githubCredentialsProvider } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n workflowId: string;\n branchOrTagName: string;\n workflowInputs?: { [key: string]: string };\n token?: string;\n }>({\n id: 'github:actions:dispatch',\n description:\n 'Dispatches a GitHub Action workflow for a given branch or tag',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl', 'workflowId', 'branchOrTagName'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n description: `Accepts the format 'github.com?repo=reponame&owner=owner' where 'reponame' is the new repository name and 'owner' is an organization or username`,\n type: 'string',\n },\n workflowId: {\n title: 'Workflow ID',\n description: 'The GitHub Action Workflow filename',\n type: 'string',\n },\n branchOrTagName: {\n title: 'Branch or Tag name',\n description:\n 'The git branch or tag name used to dispatch the workflow',\n type: 'string',\n },\n workflowInputs: {\n title: 'Workflow Inputs',\n description:\n 'Inputs keys and values to send to GitHub Action configured on the workflow file. The maximum number of properties is 10. ',\n type: 'object',\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description: 'The GITHUB_TOKEN to use for authorization to GitHub',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n workflowId,\n branchOrTagName,\n workflowInputs,\n token: providedToken,\n } = ctx.input;\n\n ctx.logger.info(\n `Dispatching workflow ${workflowId} for repo ${repoUrl} on ${branchOrTagName}`,\n );\n\n const { owner, repo } = parseRepoUrl(repoUrl, integrations);\n\n if (!owner) {\n throw new InputError('Invalid repository owner provided in repoUrl');\n }\n\n const client = new Octokit(\n await getOctokitOptions({\n integrations,\n repoUrl,\n credentialsProvider: githubCredentialsProvider,\n token: providedToken,\n }),\n );\n\n await client.rest.actions.createWorkflowDispatch({\n owner,\n repo,\n workflow_id: workflowId,\n ref: branchOrTagName,\n inputs: workflowInputs,\n });\n\n ctx.logger.info(`Workflow ${workflowId} dispatched successfully`);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n GithubCredentialsProvider,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { assertError, InputError } from '@backstage/errors';\nimport { Octokit } from 'octokit';\nimport { getOctokitOptions } from './helpers';\nimport { parseRepoUrl } from '../publish/util';\n\n/**\n * Adds labels to a pull request or issue on GitHub\n * @public\n */\nexport function createGithubIssuesLabelAction(options: {\n integrations: ScmIntegrationRegistry;\n githubCredentialsProvider?: GithubCredentialsProvider;\n}) {\n const { integrations, githubCredentialsProvider } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n number: number;\n labels: string[];\n token?: string;\n }>({\n id: 'github:issues:label',\n description: 'Adds labels to a pull request or issue on GitHub.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl', 'number', 'labels'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n description: `Accepts the format 'github.com?repo=reponame&owner=owner' where 'reponame' is the repository name and 'owner' is an organization or username`,\n type: 'string',\n },\n number: {\n title: 'Pull Request or issue number',\n description: 'The pull request or issue number to add labels to',\n type: 'number',\n },\n labels: {\n title: 'Labels',\n description: 'The labels to add to the pull request or issue',\n type: 'array',\n items: {\n type: 'string',\n },\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description: 'The GITHUB_TOKEN to use for authorization to GitHub',\n },\n },\n },\n },\n async handler(ctx) {\n const { repoUrl, number, labels, token: providedToken } = ctx.input;\n\n const { owner, repo } = parseRepoUrl(repoUrl, integrations);\n ctx.logger.info(`Adding labels to ${number} issue on repo ${repo}`);\n\n if (!owner) {\n throw new InputError('Invalid repository owner provided in repoUrl');\n }\n\n const client = new Octokit(\n await getOctokitOptions({\n integrations,\n credentialsProvider: githubCredentialsProvider,\n repoUrl: repoUrl,\n token: providedToken,\n }),\n );\n\n try {\n await client.rest.issues.addLabels({\n owner,\n repo,\n issue_number: number,\n labels,\n });\n } catch (e) {\n assertError(e);\n ctx.logger.warn(\n `Failed: adding labels to issue: '${number}' on repo: '${repo}', ${e.message}`,\n );\n }\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst repoUrl = {\n title: 'Repository Location',\n description: `Accepts the format 'github.com?repo=reponame&owner=owner' where 'reponame' is the new repository name and 'owner' is an organization or username`,\n type: 'string',\n};\nconst description = {\n title: 'Repository Description',\n type: 'string',\n};\nconst homepage = {\n title: 'Repository Homepage',\n type: 'string',\n};\nconst access = {\n title: 'Repository Access',\n description: `Sets an admin collaborator on the repository. Can either be a user reference different from 'owner' in 'repoUrl' or team reference, eg. 'org/team-name'`,\n type: 'string',\n};\nconst requireCodeOwnerReviews = {\n title: 'Require CODEOWNER Reviews?',\n description:\n 'Require an approved review in PR including files with a designated Code Owner',\n type: 'boolean',\n};\nconst dismissStaleReviews = {\n title: 'Dismiss Stale Reviews',\n description:\n 'New reviewable commits pushed to a matching branch will dismiss pull request review approvals.',\n type: 'boolean',\n};\nconst requiredStatusCheckContexts = {\n title: 'Required Status Check Contexts',\n description:\n 'The list of status checks to require in order to merge into this branch',\n type: 'array',\n items: {\n type: 'string',\n },\n};\nconst requireBranchesToBeUpToDate = {\n title: 'Require Branches To Be Up To Date?',\n description: `Require branches to be up to date before merging. The default value is 'true'`,\n type: 'boolean',\n};\nconst requiredConversationResolution = {\n title: 'Required Conversation Resolution',\n description:\n 'Requires all conversations on code to be resolved before a pull request can be merged into this branch',\n type: 'boolean',\n};\nconst repoVisibility = {\n title: 'Repository Visibility',\n type: 'string',\n enum: ['private', 'public', 'internal'],\n};\nconst deleteBranchOnMerge = {\n title: 'Delete Branch On Merge',\n type: 'boolean',\n description: `Delete the branch after merging the PR. The default value is 'false'`,\n};\nconst gitAuthorName = {\n title: 'Default Author Name',\n type: 'string',\n description: `Sets the default author name for the commit. The default value is 'Scaffolder'`,\n};\nconst gitAuthorEmail = {\n title: 'Default Author Email',\n type: 'string',\n description: `Sets the default author email for the commit.`,\n};\nconst allowMergeCommit = {\n title: 'Allow Merge Commits',\n type: 'boolean',\n description: `Allow merge commits. The default value is 'true'`,\n};\nconst allowSquashMerge = {\n title: 'Allow Squash Merges',\n type: 'boolean',\n description: `Allow squash merges. The default value is 'true'`,\n};\nconst squashMergeCommitTitle = {\n title: 'Default squash merge commit title',\n enum: ['PR_TITLE', 'COMMIT_OR_PR_TITLE'],\n description: `Sets the default value for a squash merge commit title. The default value is 'COMMIT_OR_PR_TITLE'`,\n};\nconst squashMergeCommitMessage = {\n title: 'Default squash merge commit message',\n enum: ['PR_BODY', 'COMMIT_MESSAGES', 'BLANK'],\n description: `Sets the default value for a squash merge commit message. The default value is 'COMMIT_MESSAGES'`,\n};\n\nconst allowRebaseMerge = {\n title: 'Allow Rebase Merges',\n type: 'boolean',\n description: `Allow rebase merges. The default value is 'true'`,\n};\nconst allowAutoMerge = {\n title: 'Allow Auto Merges',\n type: 'boolean',\n description: `Allow individual PRs to merge automatically when all merge requirements are met. The default value is 'false'`,\n};\nconst collaborators = {\n title: 'Collaborators',\n description: 'Provide additional users or teams with permissions',\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['access'],\n properties: {\n access: {\n type: 'string',\n description: 'The type of access for the user',\n },\n user: {\n type: 'string',\n description:\n 'The name of the user that will be added as a collaborator',\n },\n team: {\n type: 'string',\n description:\n 'The name of the team that will be added as a collaborator',\n },\n },\n oneOf: [{ required: ['user'] }, { required: ['team'] }],\n },\n};\nconst hasProjects = {\n title: 'Enable projects',\n type: 'boolean',\n description: `Enable projects for the repository. The default value is 'true' unless the organization has disabled repository projects`,\n};\nconst hasWiki = {\n title: 'Enable the wiki',\n type: 'boolean',\n description: `Enable the wiki for the repository. The default value is 'true'`,\n};\nconst hasIssues = {\n title: 'Enable issues',\n type: 'boolean',\n description: `Enable issues for the repository. The default value is 'true'`,\n};\nconst token = {\n title: 'Authentication Token',\n type: 'string',\n description: 'The token to use for authorization to GitHub',\n};\nconst topics = {\n title: 'Topics',\n type: 'array',\n items: {\n type: 'string',\n },\n};\nconst defaultBranch = {\n title: 'Default Branch',\n type: 'string',\n description: `Sets the default branch on the repository. The default value is 'master'`,\n};\nconst protectDefaultBranch = {\n title: 'Protect Default Branch',\n type: 'boolean',\n description: `Protect the default branch after creating the repository. The default value is 'true'`,\n};\nconst protectEnforceAdmins = {\n title: 'Enforce Admins On Protected Branches',\n type: 'boolean',\n description: `Enforce admins to adhere to default branch protection. The default value is 'true'`,\n};\n\nconst bypassPullRequestAllowances = {\n title: 'Bypass pull request requirements',\n description:\n 'Allow specific users, teams, or apps to bypass pull request requirements.',\n type: 'object',\n additionalProperties: false,\n properties: {\n apps: {\n type: 'array',\n items: {\n type: 'string',\n },\n },\n users: {\n type: 'array',\n items: {\n type: 'string',\n },\n },\n teams: {\n type: 'array',\n items: {\n type: 'string',\n },\n },\n },\n};\n\nconst gitCommitMessage = {\n title: 'Git Commit Message',\n type: 'string',\n description: `Sets the commit message on the repository. The default value is 'initial commit'`,\n};\nconst sourcePath = {\n title: 'Source Path',\n description:\n 'Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.',\n type: 'string',\n};\n\nconst requiredApprovingReviewCount = {\n title: 'Required approving review count',\n type: 'number',\n description: `Specify the number of reviewers required to approve pull requests. Use a number between 1 and 6 or 0 to not require reviewers. Defaults to 1.`,\n};\n\nconst restrictions = {\n title: 'Restrict who can push to the protected branch',\n description:\n 'Restrict who can push to the protected branch. User, app, and team restrictions are only available for organization-owned repositories.',\n type: 'object',\n additionalProperties: false,\n properties: {\n apps: {\n type: 'array',\n items: {\n type: 'string',\n },\n },\n users: {\n type: 'array',\n items: {\n type: 'string',\n },\n },\n teams: {\n type: 'array',\n items: {\n type: 'string',\n },\n },\n },\n};\n\nconst requiredCommitSigning = {\n title: 'Require commit signing',\n type: 'boolean',\n description: `Require commit signing so that you must sign commits on this branch.`,\n};\n\nconst repoVariables = {\n title: 'Repository Variables',\n description: `Variables attached to the repository`,\n type: 'object',\n};\n\nconst secrets = {\n title: 'Repository Secrets',\n description: `Secrets attached to the repository`,\n type: 'object',\n};\n\nexport { access };\nexport { allowMergeCommit };\nexport { allowRebaseMerge };\nexport { allowSquashMerge };\nexport { squashMergeCommitTitle };\nexport { squashMergeCommitMessage };\nexport { allowAutoMerge };\nexport { collaborators };\nexport { defaultBranch };\nexport { deleteBranchOnMerge };\nexport { description };\nexport { gitAuthorEmail };\nexport { gitAuthorName };\nexport { gitCommitMessage };\nexport { homepage };\nexport { protectDefaultBranch };\nexport { protectEnforceAdmins };\nexport { bypassPullRequestAllowances };\nexport { requiredApprovingReviewCount };\nexport { restrictions };\nexport { repoUrl };\nexport { repoVisibility };\nexport { requireCodeOwnerReviews };\nexport { dismissStaleReviews };\nexport { requiredStatusCheckContexts };\nexport { requireBranchesToBeUpToDate };\nexport { requiredConversationResolution };\nexport { hasProjects };\nexport { hasIssues };\nexport { hasWiki };\nexport { sourcePath };\nexport { token };\nexport { topics };\nexport { requiredCommitSigning };\nexport { repoVariables };\nexport { secrets };\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst remoteUrl = {\n title: 'A URL to the repository with the provider',\n type: 'string',\n};\nconst repoContentsUrl = {\n title: 'A URL to the root of the repository',\n type: 'string',\n};\n\nconst commitHash = {\n title: 'The git commit hash of the initial commit',\n type: 'string',\n};\n\nexport { remoteUrl };\nexport { repoContentsUrl };\nexport { commitHash };\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport {\n GithubCredentialsProvider,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { Octokit } from 'octokit';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { parseRepoUrl } from '../publish/util';\nimport {\n createGithubRepoWithCollaboratorsAndTopics,\n getOctokitOptions,\n} from './helpers';\nimport * as inputProps from './inputProperties';\nimport * as outputProps from './outputProperties';\n\n/**\n * Creates a new action that initializes a git repository\n *\n * @public\n */\nexport function createGithubRepoCreateAction(options: {\n integrations: ScmIntegrationRegistry;\n githubCredentialsProvider?: GithubCredentialsProvider;\n}) {\n const { integrations, githubCredentialsProvider } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n description?: string;\n homepage?: string;\n access?: string;\n deleteBranchOnMerge?: boolean;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n allowRebaseMerge?: boolean;\n allowSquashMerge?: boolean;\n squashMergeCommitTitle?: 'PR_TITLE' | 'COMMIT_OR_PR_TITLE';\n squashMergeCommitMessage?: 'PR_BODY' | 'COMMIT_MESSAGES' | 'BLANK';\n allowMergeCommit?: boolean;\n allowAutoMerge?: boolean;\n requireCodeOwnerReviews?: boolean;\n bypassPullRequestAllowances?: {\n users?: string[];\n teams?: string[];\n apps?: string[];\n };\n requiredApprovingReviewCount?: number;\n restrictions?: {\n users: string[];\n teams: string[];\n apps?: string[];\n };\n requiredStatusCheckContexts?: string[];\n requireBranchesToBeUpToDate?: boolean;\n requiredConversationResolution?: boolean;\n repoVisibility?: 'private' | 'internal' | 'public';\n collaborators?: Array<\n | {\n user: string;\n access: string;\n }\n | {\n team: string;\n access: string;\n }\n | {\n /** @deprecated This field is deprecated in favor of team */\n username: string;\n access: 'pull' | 'push' | 'admin' | 'maintain' | 'triage';\n }\n >;\n hasProjects?: boolean;\n hasWiki?: boolean;\n hasIssues?: boolean;\n token?: string;\n topics?: string[];\n repoVariables?: { [key: string]: string };\n secrets?: { [key: string]: string };\n requireCommitSigning?: boolean;\n }>({\n id: 'github:repo:create',\n description: 'Creates a GitHub repository.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: inputProps.repoUrl,\n description: inputProps.description,\n homepage: inputProps.homepage,\n access: inputProps.access,\n requireCodeOwnerReviews: inputProps.requireCodeOwnerReviews,\n bypassPullRequestAllowances: inputProps.bypassPullRequestAllowances,\n requiredApprovingReviewCount: inputProps.requiredApprovingReviewCount,\n restrictions: inputProps.restrictions,\n requiredStatusCheckContexts: inputProps.requiredStatusCheckContexts,\n requireBranchesToBeUpToDate: inputProps.requireBranchesToBeUpToDate,\n requiredConversationResolution:\n inputProps.requiredConversationResolution,\n repoVisibility: inputProps.repoVisibility,\n deleteBranchOnMerge: inputProps.deleteBranchOnMerge,\n allowMergeCommit: inputProps.allowMergeCommit,\n allowSquashMerge: inputProps.allowSquashMerge,\n squashMergeCommitTitle: inputProps.squashMergeCommitTitle,\n squashMergeCommitMessage: inputProps.squashMergeCommitMessage,\n allowRebaseMerge: inputProps.allowRebaseMerge,\n allowAutoMerge: inputProps.allowAutoMerge,\n collaborators: inputProps.collaborators,\n hasProjects: inputProps.hasProjects,\n hasWiki: inputProps.hasWiki,\n hasIssues: inputProps.hasIssues,\n token: inputProps.token,\n topics: inputProps.topics,\n repoVariables: inputProps.repoVariables,\n secrets: inputProps.secrets,\n requiredCommitSigning: inputProps.requiredCommitSigning,\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: outputProps.remoteUrl,\n repoContentsUrl: outputProps.repoContentsUrl,\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n description,\n homepage,\n access,\n repoVisibility = 'private',\n deleteBranchOnMerge = false,\n allowMergeCommit = true,\n allowSquashMerge = true,\n squashMergeCommitTitle = 'COMMIT_OR_PR_TITLE',\n squashMergeCommitMessage = 'COMMIT_MESSAGES',\n allowRebaseMerge = true,\n allowAutoMerge = false,\n collaborators,\n hasProjects = undefined,\n hasWiki = undefined,\n hasIssues = undefined,\n topics,\n repoVariables,\n secrets,\n token: providedToken,\n } = ctx.input;\n\n const octokitOptions = await getOctokitOptions({\n integrations,\n credentialsProvider: githubCredentialsProvider,\n token: providedToken,\n repoUrl: repoUrl,\n });\n const client = new Octokit(octokitOptions);\n\n const { owner, repo } = parseRepoUrl(repoUrl, integrations);\n\n if (!owner) {\n throw new InputError('Invalid repository owner provided in repoUrl');\n }\n\n const newRepo = await createGithubRepoWithCollaboratorsAndTopics(\n client,\n repo,\n owner,\n repoVisibility,\n description,\n homepage,\n deleteBranchOnMerge,\n allowMergeCommit,\n allowSquashMerge,\n squashMergeCommitTitle,\n squashMergeCommitMessage,\n allowRebaseMerge,\n allowAutoMerge,\n access,\n collaborators,\n hasProjects,\n hasWiki,\n hasIssues,\n topics,\n repoVariables,\n secrets,\n ctx.logger,\n );\n\n ctx.output('remoteUrl', newRepo.clone_url);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { InputError } from '@backstage/errors';\nimport {\n GithubCredentialsProvider,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { Octokit } from 'octokit';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { parseRepoUrl } from '../publish/util';\nimport { getOctokitOptions, initRepoPushAndProtect } from './helpers';\nimport * as inputProps from './inputProperties';\nimport * as outputProps from './outputProperties';\n\n/**\n * Creates a new action that initializes a git repository of the content in the workspace\n * and publishes it to GitHub.\n *\n * @public\n */\nexport function createGithubRepoPushAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n githubCredentialsProvider?: GithubCredentialsProvider;\n}) {\n const { integrations, config, githubCredentialsProvider } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n description?: string;\n defaultBranch?: string;\n protectDefaultBranch?: boolean;\n protectEnforceAdmins?: boolean;\n gitCommitMessage?: string;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n requireCodeOwnerReviews?: boolean;\n dismissStaleReviews?: boolean;\n bypassPullRequestAllowances?:\n | {\n users?: string[];\n teams?: string[];\n apps?: string[];\n }\n | undefined;\n requiredApprovingReviewCount?: number;\n restrictions?:\n | {\n users: string[];\n teams: string[];\n apps?: string[];\n }\n | undefined;\n requiredStatusCheckContexts?: string[];\n requireBranchesToBeUpToDate?: boolean;\n requiredConversationResolution?: boolean;\n sourcePath?: string;\n token?: string;\n requiredCommitSigning?: boolean;\n }>({\n id: 'github:repo:push',\n description:\n 'Initializes a git repository of contents in workspace and publishes it to GitHub.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: inputProps.repoUrl,\n requireCodeOwnerReviews: inputProps.requireCodeOwnerReviews,\n dismissStaleReviews: inputProps.dismissStaleReviews,\n requiredStatusCheckContexts: inputProps.requiredStatusCheckContexts,\n bypassPullRequestAllowances: inputProps.bypassPullRequestAllowances,\n requiredApprovingReviewCount: inputProps.requiredApprovingReviewCount,\n restrictions: inputProps.restrictions,\n requireBranchesToBeUpToDate: inputProps.requireBranchesToBeUpToDate,\n requiredConversationResolution:\n inputProps.requiredConversationResolution,\n defaultBranch: inputProps.defaultBranch,\n protectDefaultBranch: inputProps.protectDefaultBranch,\n protectEnforceAdmins: inputProps.protectEnforceAdmins,\n gitCommitMessage: inputProps.gitCommitMessage,\n gitAuthorName: inputProps.gitAuthorName,\n gitAuthorEmail: inputProps.gitAuthorEmail,\n sourcePath: inputProps.sourcePath,\n token: inputProps.token,\n requiredCommitSigning: inputProps.requiredCommitSigning,\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: outputProps.remoteUrl,\n repoContentsUrl: outputProps.repoContentsUrl,\n commitHash: outputProps.commitHash,\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n defaultBranch = 'master',\n protectDefaultBranch = true,\n protectEnforceAdmins = true,\n gitCommitMessage = 'initial commit',\n gitAuthorName,\n gitAuthorEmail,\n requireCodeOwnerReviews = false,\n dismissStaleReviews = false,\n bypassPullRequestAllowances,\n requiredApprovingReviewCount = 1,\n restrictions,\n requiredStatusCheckContexts = [],\n requireBranchesToBeUpToDate = true,\n requiredConversationResolution = false,\n token: providedToken,\n requiredCommitSigning = false,\n } = ctx.input;\n\n const { owner, repo } = parseRepoUrl(repoUrl, integrations);\n\n if (!owner) {\n throw new InputError('Invalid repository owner provided in repoUrl');\n }\n\n const octokitOptions = await getOctokitOptions({\n integrations,\n credentialsProvider: githubCredentialsProvider,\n token: providedToken,\n repoUrl,\n });\n\n const client = new Octokit(octokitOptions);\n\n const targetRepo = await client.rest.repos.get({ owner, repo });\n\n const remoteUrl = targetRepo.data.clone_url;\n const repoContentsUrl = `${targetRepo.data.html_url}/blob/${defaultBranch}`;\n\n const { commitHash } = await initRepoPushAndProtect(\n remoteUrl,\n octokitOptions.auth,\n ctx.workspacePath,\n ctx.input.sourcePath,\n defaultBranch,\n protectDefaultBranch,\n protectEnforceAdmins,\n owner,\n client,\n repo,\n requireCodeOwnerReviews,\n bypassPullRequestAllowances,\n requiredApprovingReviewCount,\n restrictions,\n requiredStatusCheckContexts,\n requireBranchesToBeUpToDate,\n requiredConversationResolution,\n config,\n ctx.logger,\n gitCommitMessage,\n gitAuthorName,\n gitAuthorEmail,\n dismissStaleReviews,\n requiredCommitSigning,\n );\n\n ctx.output('remoteUrl', remoteUrl);\n ctx.output('repoContentsUrl', repoContentsUrl);\n ctx.output('commitHash', commitHash);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n GithubCredentialsProvider,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { emitterEventNames } from '@octokit/webhooks';\nimport { assertError, InputError } from '@backstage/errors';\nimport { Octokit } from 'octokit';\nimport { getOctokitOptions } from './helpers';\nimport { parseRepoUrl } from '../publish/util';\n\n/**\n * Creates new action that creates a webhook for a repository on GitHub.\n * @public\n */\nexport function createGithubWebhookAction(options: {\n integrations: ScmIntegrationRegistry;\n defaultWebhookSecret?: string;\n githubCredentialsProvider?: GithubCredentialsProvider;\n}) {\n const { integrations, defaultWebhookSecret, githubCredentialsProvider } =\n options;\n\n const eventNames = emitterEventNames.filter(event => !event.includes('.'));\n\n return createTemplateAction<{\n repoUrl: string;\n webhookUrl: string;\n webhookSecret?: string;\n events?: string[];\n active?: boolean;\n contentType?: 'form' | 'json';\n insecureSsl?: boolean;\n token?: string;\n }>({\n id: 'github:webhook',\n description: 'Creates webhook for a repository on GitHub.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl', 'webhookUrl'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n description: `Accepts the format 'github.com?repo=reponame&owner=owner' where 'reponame' is the new repository name and 'owner' is an organization or username`,\n type: 'string',\n },\n webhookUrl: {\n title: 'Webhook URL',\n description: 'The URL to which the payloads will be delivered',\n type: 'string',\n },\n webhookSecret: {\n title: 'Webhook Secret',\n description:\n 'Webhook secret value. The default can be provided internally in action creation',\n type: 'string',\n },\n events: {\n title: 'Triggering Events',\n description:\n 'Determines what events the hook is triggered for. Default: push',\n type: 'array',\n oneOf: [\n {\n items: {\n type: 'string',\n enum: eventNames,\n },\n },\n {\n items: {\n type: 'string',\n const: '*',\n },\n },\n ],\n },\n active: {\n title: 'Active',\n type: 'boolean',\n description: `Determines if notifications are sent when the webhook is triggered. Default: true`,\n },\n contentType: {\n title: 'Content Type',\n type: 'string',\n enum: ['form', 'json'],\n description: `The media type used to serialize the payloads. The default is 'form'`,\n },\n insecureSsl: {\n title: 'Insecure SSL',\n type: 'boolean',\n description: `Determines whether the SSL certificate of the host for url will be verified when delivering payloads. Default 'false'`,\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description: 'The GITHUB_TOKEN to use for authorization to GitHub',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n webhookUrl,\n webhookSecret = defaultWebhookSecret,\n events = ['push'],\n active = true,\n contentType = 'form',\n insecureSsl = false,\n token: providedToken,\n } = ctx.input;\n\n ctx.logger.info(`Creating webhook ${webhookUrl} for repo ${repoUrl}`);\n const { owner, repo } = parseRepoUrl(repoUrl, integrations);\n\n if (!owner) {\n throw new InputError('Invalid repository owner provided in repoUrl');\n }\n\n const client = new Octokit(\n await getOctokitOptions({\n integrations,\n credentialsProvider: githubCredentialsProvider,\n repoUrl: repoUrl,\n token: providedToken,\n }),\n );\n\n try {\n const insecure_ssl = insecureSsl ? '1' : '0';\n await client.rest.repos.createWebhook({\n owner,\n repo,\n config: {\n url: webhookUrl,\n content_type: contentType,\n secret: webhookSecret,\n insecure_ssl,\n },\n events,\n active,\n });\n ctx.logger.info(`Webhook '${webhookUrl}' created successfully`);\n } catch (e) {\n assertError(e);\n ctx.logger.warn(\n `Failed: create webhook '${webhookUrl}' on repo: '${repo}', ${e.message}`,\n );\n }\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport { initRepoAndPush } from '../helpers';\nimport { GitRepositoryCreateOptions } from 'azure-devops-node-api/interfaces/GitInterfaces';\nimport { getPersonalAccessTokenHandler, WebApi } from 'azure-devops-node-api';\nimport { getRepoSourceDirectory, parseRepoUrl } from './util';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { Config } from '@backstage/config';\n\n/**\n * Creates a new action that initializes a git repository of the content in the workspace\n * and publishes it to Azure.\n * @public\n */\nexport function createPublishAzureAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n}) {\n const { integrations, config } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n description?: string;\n defaultBranch?: string;\n sourcePath?: string;\n token?: string;\n gitCommitMessage?: string;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n }>({\n id: 'publish:azure',\n description:\n 'Initializes a git repository of the content in the workspace, and publishes it to Azure.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n type: 'string',\n },\n description: {\n title: 'Repository Description',\n type: 'string',\n },\n defaultBranch: {\n title: 'Default Branch',\n type: 'string',\n description: `Sets the default branch on the repository. The default value is 'master'`,\n },\n gitCommitMessage: {\n title: 'Git Commit Message',\n type: 'string',\n description: `Sets the commit message on the repository. The default value is 'initial commit'`,\n },\n gitAuthorName: {\n title: 'Default Author Name',\n type: 'string',\n description: `Sets the default author name for the commit. The default value is 'Scaffolder'`,\n },\n gitAuthorEmail: {\n title: 'Default Author Email',\n type: 'string',\n description: `Sets the default author email for the commit.`,\n },\n sourcePath: {\n title: 'Source Path',\n description:\n 'Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.',\n type: 'string',\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description: 'The token to use for authorization to Azure',\n },\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: {\n title: 'A URL to the repository with the provider',\n type: 'string',\n },\n repoContentsUrl: {\n title: 'A URL to the root of the repository',\n type: 'string',\n },\n repositoryId: {\n title: 'The Id of the created repository',\n type: 'string',\n },\n commitHash: {\n title: 'The git commit hash of the initial commit',\n type: 'string',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n defaultBranch = 'master',\n gitCommitMessage = 'initial commit',\n gitAuthorName,\n gitAuthorEmail,\n } = ctx.input;\n\n const { owner, repo, host, organization } = parseRepoUrl(\n repoUrl,\n integrations,\n );\n\n if (!organization) {\n throw new InputError(\n `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing organization`,\n );\n }\n\n const integrationConfig = integrations.azure.byHost(host);\n\n if (!integrationConfig) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n if (!integrationConfig.config.token && !ctx.input.token) {\n throw new InputError(`No token provided for Azure Integration ${host}`);\n }\n\n const token = ctx.input.token ?? integrationConfig.config.token!;\n const authHandler = getPersonalAccessTokenHandler(token);\n\n const webApi = new WebApi(`https://${host}/${organization}`, authHandler);\n const client = await webApi.getGitApi();\n const createOptions: GitRepositoryCreateOptions = { name: repo };\n const returnedRepo = await client.createRepository(createOptions, owner);\n\n if (!returnedRepo) {\n throw new InputError(\n `Unable to create the repository with Organization ${organization}, Project ${owner} and Repo ${repo}.\n Please make sure that both the Org and Project are typed corrected and exist.`,\n );\n }\n const remoteUrl = returnedRepo.remoteUrl;\n\n if (!remoteUrl) {\n throw new InputError(\n 'No remote URL returned from create repository for Azure',\n );\n }\n const repositoryId = returnedRepo.id;\n\n if (!repositoryId) {\n throw new InputError('No Id returned from create repository for Azure');\n }\n\n // blam: Repo contents is serialized into the path,\n // so it's just the base path I think\n const repoContentsUrl = remoteUrl;\n\n const gitAuthorInfo = {\n name: gitAuthorName\n ? gitAuthorName\n : config.getOptionalString('scaffolder.defaultAuthor.name'),\n email: gitAuthorEmail\n ? gitAuthorEmail\n : config.getOptionalString('scaffolder.defaultAuthor.email'),\n };\n\n const commitResult = await initRepoAndPush({\n dir: getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),\n remoteUrl,\n defaultBranch,\n auth: {\n username: 'notempty',\n password: token,\n },\n logger: ctx.logger,\n commitMessage: gitCommitMessage\n ? gitCommitMessage\n : config.getOptionalString('scaffolder.defaultCommitMessage'),\n gitAuthorInfo,\n });\n\n ctx.output('commitHash', commitResult?.commitHash);\n ctx.output('remoteUrl', remoteUrl);\n ctx.output('repoContentsUrl', repoContentsUrl);\n ctx.output('repositoryId', repositoryId);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport {\n BitbucketIntegrationConfig,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport fetch, { Response, RequestInit } from 'node-fetch';\nimport { initRepoAndPush } from '../helpers';\nimport { getRepoSourceDirectory, parseRepoUrl } from './util';\nimport { Config } from '@backstage/config';\n\nconst createBitbucketCloudRepository = async (opts: {\n workspace: string;\n project: string;\n repo: string;\n description?: string;\n repoVisibility: 'private' | 'public';\n mainBranch: string;\n authorization: string;\n apiBaseUrl: string;\n}) => {\n const {\n workspace,\n project,\n repo,\n description,\n repoVisibility,\n mainBranch,\n authorization,\n apiBaseUrl,\n } = opts;\n\n const options: RequestInit = {\n method: 'POST',\n body: JSON.stringify({\n scm: 'git',\n description: description,\n is_private: repoVisibility === 'private',\n project: { key: project },\n }),\n headers: {\n Authorization: authorization,\n 'Content-Type': 'application/json',\n },\n };\n\n let response: Response;\n try {\n response = await fetch(\n `${apiBaseUrl}/repositories/${workspace}/${repo}`,\n options,\n );\n } catch (e) {\n throw new Error(`Unable to create repository, ${e}`);\n }\n\n if (response.status !== 200) {\n throw new Error(\n `Unable to create repository, ${response.status} ${\n response.statusText\n }, ${await response.text()}`,\n );\n }\n\n const r = await response.json();\n let remoteUrl = '';\n for (const link of r.links.clone) {\n if (link.name === 'https') {\n remoteUrl = link.href;\n }\n }\n\n // \"mainbranch.name\" cannot be set neither at create nor update of the repo\n // the first pushed branch will be set as \"main branch\" then\n const repoContentsUrl = `${r.links.html.href}/src/${mainBranch}`;\n return { remoteUrl, repoContentsUrl };\n};\n\nconst createBitbucketServerRepository = async (opts: {\n project: string;\n repo: string;\n description?: string;\n repoVisibility: 'private' | 'public';\n authorization: string;\n apiBaseUrl: string;\n}) => {\n const {\n project,\n repo,\n description,\n authorization,\n repoVisibility,\n apiBaseUrl,\n } = opts;\n\n let response: Response;\n const options: RequestInit = {\n method: 'POST',\n body: JSON.stringify({\n name: repo,\n description: description,\n public: repoVisibility === 'public',\n }),\n headers: {\n Authorization: authorization,\n 'Content-Type': 'application/json',\n },\n };\n\n try {\n response = await fetch(`${apiBaseUrl}/projects/${project}/repos`, options);\n } catch (e) {\n throw new Error(`Unable to create repository, ${e}`);\n }\n\n if (response.status !== 201) {\n throw new Error(\n `Unable to create repository, ${response.status} ${\n response.statusText\n }, ${await response.text()}`,\n );\n }\n\n const r = await response.json();\n let remoteUrl = '';\n for (const link of r.links.clone) {\n if (link.name === 'http') {\n remoteUrl = link.href;\n }\n }\n\n const repoContentsUrl = `${r.links.self[0].href}`;\n return { remoteUrl, repoContentsUrl };\n};\n\nconst getAuthorizationHeader = (config: BitbucketIntegrationConfig) => {\n if (config.username && config.appPassword) {\n const buffer = Buffer.from(\n `${config.username}:${config.appPassword}`,\n 'utf8',\n );\n\n return `Basic ${buffer.toString('base64')}`;\n }\n\n if (config.token) {\n return `Bearer ${config.token}`;\n }\n\n throw new Error(\n `Authorization has not been provided for Bitbucket. Please add either username + appPassword or token to the Integrations config`,\n );\n};\n\nconst performEnableLFS = async (opts: {\n authorization: string;\n host: string;\n project: string;\n repo: string;\n}) => {\n const { authorization, host, project, repo } = opts;\n\n const options: RequestInit = {\n method: 'PUT',\n headers: {\n Authorization: authorization,\n },\n };\n\n const { ok, status, statusText } = await fetch(\n `https://${host}/rest/git-lfs/admin/projects/${project}/repos/${repo}/enabled`,\n options,\n );\n\n if (!ok)\n throw new Error(\n `Failed to enable LFS in the repository, ${status}: ${statusText}`,\n );\n};\n\n/**\n * Creates a new action that initializes a git repository of the content in the workspace\n * and publishes it to Bitbucket.\n * @public\n * @deprecated in favor of createPublishBitbucketCloudAction and createPublishBitbucketServerAction\n */\nexport function createPublishBitbucketAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n}) {\n const { integrations, config } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n description?: string;\n defaultBranch?: string;\n repoVisibility?: 'private' | 'public';\n sourcePath?: string;\n enableLFS?: boolean;\n token?: string;\n gitCommitMessage?: string;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n }>({\n id: 'publish:bitbucket',\n description:\n 'Initializes a git repository of the content in the workspace, and publishes it to Bitbucket.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n type: 'string',\n },\n description: {\n title: 'Repository Description',\n type: 'string',\n },\n repoVisibility: {\n title: 'Repository Visibility',\n type: 'string',\n enum: ['private', 'public'],\n },\n defaultBranch: {\n title: 'Default Branch',\n type: 'string',\n description: `Sets the default branch on the repository. The default value is 'master'`,\n },\n sourcePath: {\n title: 'Source Path',\n description:\n 'Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.',\n type: 'string',\n },\n enableLFS: {\n title: 'Enable LFS?',\n description:\n 'Enable LFS for the repository. Only available for hosted Bitbucket.',\n type: 'boolean',\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description: 'The token to use for authorization to BitBucket',\n },\n gitCommitMessage: {\n title: 'Git Commit Message',\n type: 'string',\n description: `Sets the commit message on the repository. The default value is 'initial commit'`,\n },\n gitAuthorName: {\n title: 'Default Author Name',\n type: 'string',\n description: `Sets the default author name for the commit. The default value is 'Scaffolder'`,\n },\n gitAuthorEmail: {\n title: 'Default Author Email',\n type: 'string',\n description: `Sets the default author email for the commit.`,\n },\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: {\n title: 'A URL to the repository with the provider',\n type: 'string',\n },\n repoContentsUrl: {\n title: 'A URL to the root of the repository',\n type: 'string',\n },\n commitHash: {\n title: 'The git commit hash of the initial commit',\n type: 'string',\n },\n },\n },\n },\n async handler(ctx) {\n ctx.logger.warn(\n `[Deprecated] Please migrate the use of action \"publish:bitbucket\" to \"publish:bitbucketCloud\" or \"publish:bitbucketServer\".`,\n );\n const {\n repoUrl,\n description,\n defaultBranch = 'master',\n repoVisibility = 'private',\n enableLFS = false,\n gitCommitMessage = 'initial commit',\n gitAuthorName,\n gitAuthorEmail,\n } = ctx.input;\n\n const { workspace, project, repo, host } = parseRepoUrl(\n repoUrl,\n integrations,\n );\n\n // Workspace is only required for bitbucket cloud\n if (host === 'bitbucket.org') {\n if (!workspace) {\n throw new InputError(\n `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`,\n );\n }\n }\n\n // Project is required for both bitbucket cloud and bitbucket server\n if (!project) {\n throw new InputError(\n `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`,\n );\n }\n\n const integrationConfig = integrations.bitbucket.byHost(host);\n\n if (!integrationConfig) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n const authorization = getAuthorizationHeader(\n ctx.input.token\n ? {\n host: integrationConfig.config.host,\n apiBaseUrl: integrationConfig.config.apiBaseUrl,\n token: ctx.input.token,\n }\n : integrationConfig.config,\n );\n\n const apiBaseUrl = integrationConfig.config.apiBaseUrl;\n\n const createMethod =\n host === 'bitbucket.org'\n ? createBitbucketCloudRepository\n : createBitbucketServerRepository;\n\n const { remoteUrl, repoContentsUrl } = await createMethod({\n authorization,\n workspace: workspace || '',\n project,\n repo,\n repoVisibility,\n mainBranch: defaultBranch,\n description,\n apiBaseUrl,\n });\n\n const gitAuthorInfo = {\n name: gitAuthorName\n ? gitAuthorName\n : config.getOptionalString('scaffolder.defaultAuthor.name'),\n email: gitAuthorEmail\n ? gitAuthorEmail\n : config.getOptionalString('scaffolder.defaultAuthor.email'),\n };\n\n let auth;\n\n if (ctx.input.token) {\n auth = {\n username: 'x-token-auth',\n password: ctx.input.token,\n };\n } else {\n auth = {\n username: integrationConfig.config.username\n ? integrationConfig.config.username\n : 'x-token-auth',\n password: integrationConfig.config.appPassword\n ? integrationConfig.config.appPassword\n : integrationConfig.config.token ?? '',\n };\n }\n\n const commitResult = await initRepoAndPush({\n dir: getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),\n remoteUrl,\n auth,\n defaultBranch,\n logger: ctx.logger,\n commitMessage: gitCommitMessage\n ? gitCommitMessage\n : config.getOptionalString('scaffolder.defaultCommitMessage'),\n gitAuthorInfo,\n });\n\n if (enableLFS && host !== 'bitbucket.org') {\n await performEnableLFS({ authorization, host, project, repo });\n }\n\n ctx.output('commitHash', commitResult?.commitHash);\n ctx.output('remoteUrl', remoteUrl);\n ctx.output('repoContentsUrl', repoContentsUrl);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport fetch, { Response, RequestInit } from 'node-fetch';\nimport { initRepoAndPush } from '../helpers';\nimport { getRepoSourceDirectory, parseRepoUrl } from './util';\nimport { Config } from '@backstage/config';\n\nconst createRepository = async (opts: {\n workspace: string;\n project: string;\n repo: string;\n description?: string;\n repoVisibility: 'private' | 'public';\n mainBranch: string;\n authorization: string;\n apiBaseUrl: string;\n}) => {\n const {\n workspace,\n project,\n repo,\n description,\n repoVisibility,\n mainBranch,\n authorization,\n apiBaseUrl,\n } = opts;\n\n const options: RequestInit = {\n method: 'POST',\n body: JSON.stringify({\n scm: 'git',\n description: description,\n is_private: repoVisibility === 'private',\n project: { key: project },\n }),\n headers: {\n Authorization: authorization,\n 'Content-Type': 'application/json',\n },\n };\n\n let response: Response;\n try {\n response = await fetch(\n `${apiBaseUrl}/repositories/${workspace}/${repo}`,\n options,\n );\n } catch (e) {\n throw new Error(`Unable to create repository, ${e}`);\n }\n\n if (response.status !== 200) {\n throw new Error(\n `Unable to create repository, ${response.status} ${\n response.statusText\n }, ${await response.text()}`,\n );\n }\n\n const r = await response.json();\n let remoteUrl = '';\n for (const link of r.links.clone) {\n if (link.name === 'https') {\n remoteUrl = link.href;\n }\n }\n\n // \"mainbranch.name\" cannot be set neither at create nor update of the repo\n // the first pushed branch will be set as \"main branch\" then\n const repoContentsUrl = `${r.links.html.href}/src/${mainBranch}`;\n return { remoteUrl, repoContentsUrl };\n};\n\nconst getAuthorizationHeader = (config: {\n username?: string;\n appPassword?: string;\n token?: string;\n}) => {\n if (config.username && config.appPassword) {\n const buffer = Buffer.from(\n `${config.username}:${config.appPassword}`,\n 'utf8',\n );\n\n return `Basic ${buffer.toString('base64')}`;\n }\n\n if (config.token) {\n return `Bearer ${config.token}`;\n }\n\n throw new Error(\n `Authorization has not been provided for Bitbucket Cloud. Please add either username + appPassword to the Integrations config or a user login auth token`,\n );\n};\n\n/**\n * Creates a new action that initializes a git repository of the content in the workspace\n * and publishes it to Bitbucket Cloud.\n * @public\n */\nexport function createPublishBitbucketCloudAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n}) {\n const { integrations, config } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n description?: string;\n defaultBranch?: string;\n repoVisibility?: 'private' | 'public';\n sourcePath?: string;\n token?: string;\n }>({\n id: 'publish:bitbucketCloud',\n description:\n 'Initializes a git repository of the content in the workspace, and publishes it to Bitbucket Cloud.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n type: 'string',\n },\n description: {\n title: 'Repository Description',\n type: 'string',\n },\n repoVisibility: {\n title: 'Repository Visibility',\n type: 'string',\n enum: ['private', 'public'],\n },\n defaultBranch: {\n title: 'Default Branch',\n type: 'string',\n description: `Sets the default branch on the repository. The default value is 'master'`,\n },\n sourcePath: {\n title: 'Source Path',\n description:\n 'Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.',\n type: 'string',\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description:\n 'The token to use for authorization to BitBucket Cloud',\n },\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: {\n title: 'A URL to the repository with the provider',\n type: 'string',\n },\n repoContentsUrl: {\n title: 'A URL to the root of the repository',\n type: 'string',\n },\n commitHash: {\n title: 'The git commit hash of the initial commit',\n type: 'string',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n description,\n defaultBranch = 'master',\n repoVisibility = 'private',\n } = ctx.input;\n\n const { workspace, project, repo, host } = parseRepoUrl(\n repoUrl,\n integrations,\n );\n\n if (!workspace) {\n throw new InputError(\n `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`,\n );\n }\n\n if (!project) {\n throw new InputError(\n `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`,\n );\n }\n\n const integrationConfig = integrations.bitbucketCloud.byHost(host);\n if (!integrationConfig) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n const authorization = getAuthorizationHeader(\n ctx.input.token ? { token: ctx.input.token } : integrationConfig.config,\n );\n\n const apiBaseUrl = integrationConfig.config.apiBaseUrl;\n\n const { remoteUrl, repoContentsUrl } = await createRepository({\n authorization,\n workspace: workspace || '',\n project,\n repo,\n repoVisibility,\n mainBranch: defaultBranch,\n description,\n apiBaseUrl,\n });\n\n const gitAuthorInfo = {\n name: config.getOptionalString('scaffolder.defaultAuthor.name'),\n email: config.getOptionalString('scaffolder.defaultAuthor.email'),\n };\n\n let auth;\n\n if (ctx.input.token) {\n auth = {\n username: 'x-token-auth',\n password: ctx.input.token,\n };\n } else {\n if (\n !integrationConfig.config.username ||\n !integrationConfig.config.appPassword\n ) {\n throw new Error(\n 'Credentials for Bitbucket Cloud integration required for this action.',\n );\n }\n\n auth = {\n username: integrationConfig.config.username,\n password: integrationConfig.config.appPassword,\n };\n }\n\n const commitResult = await initRepoAndPush({\n dir: getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),\n remoteUrl,\n auth,\n defaultBranch,\n logger: ctx.logger,\n commitMessage: config.getOptionalString(\n 'scaffolder.defaultCommitMessage',\n ),\n gitAuthorInfo,\n });\n\n ctx.output('commitHash', commitResult?.commitHash);\n ctx.output('remoteUrl', remoteUrl);\n ctx.output('repoContentsUrl', repoContentsUrl);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport {\n getBitbucketServerRequestOptions,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport fetch, { Response, RequestInit } from 'node-fetch';\nimport { initRepoAndPush } from '../helpers';\nimport { getRepoSourceDirectory, parseRepoUrl } from './util';\nimport { Config } from '@backstage/config';\n\nconst createRepository = async (opts: {\n project: string;\n repo: string;\n description?: string;\n repoVisibility: 'private' | 'public';\n defaultBranch: string;\n authorization: string;\n apiBaseUrl: string;\n}) => {\n const {\n project,\n repo,\n description,\n authorization,\n repoVisibility,\n defaultBranch,\n apiBaseUrl,\n } = opts;\n\n let response: Response;\n const options: RequestInit = {\n method: 'POST',\n body: JSON.stringify({\n name: repo,\n description: description,\n defaultBranch: defaultBranch,\n public: repoVisibility === 'public',\n }),\n headers: {\n Authorization: authorization,\n 'Content-Type': 'application/json',\n },\n };\n\n try {\n response = await fetch(`${apiBaseUrl}/projects/${project}/repos`, options);\n } catch (e) {\n throw new Error(`Unable to create repository, ${e}`);\n }\n\n if (response.status !== 201) {\n throw new Error(\n `Unable to create repository, ${response.status} ${\n response.statusText\n }, ${await response.text()}`,\n );\n }\n\n const r = await response.json();\n let remoteUrl = '';\n for (const link of r.links.clone) {\n if (link.name === 'http') {\n remoteUrl = link.href;\n }\n }\n\n const repoContentsUrl = `${r.links.self[0].href}`;\n return { remoteUrl, repoContentsUrl };\n};\n\nconst performEnableLFS = async (opts: {\n authorization: string;\n host: string;\n project: string;\n repo: string;\n}) => {\n const { authorization, host, project, repo } = opts;\n\n const options: RequestInit = {\n method: 'PUT',\n headers: {\n Authorization: authorization,\n },\n };\n\n const { ok, status, statusText } = await fetch(\n `https://${host}/rest/git-lfs/admin/projects/${project}/repos/${repo}/enabled`,\n options,\n );\n\n if (!ok)\n throw new Error(\n `Failed to enable LFS in the repository, ${status}: ${statusText}`,\n );\n};\n\n/**\n * Creates a new action that initializes a git repository of the content in the workspace\n * and publishes it to Bitbucket Server.\n * @public\n */\nexport function createPublishBitbucketServerAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n}) {\n const { integrations, config } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n description?: string;\n defaultBranch?: string;\n repoVisibility?: 'private' | 'public';\n sourcePath?: string;\n enableLFS?: boolean;\n token?: string;\n gitCommitMessage?: string;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n }>({\n id: 'publish:bitbucketServer',\n description:\n 'Initializes a git repository of the content in the workspace, and publishes it to Bitbucket Server.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n type: 'string',\n },\n description: {\n title: 'Repository Description',\n type: 'string',\n },\n repoVisibility: {\n title: 'Repository Visibility',\n type: 'string',\n enum: ['private', 'public'],\n },\n defaultBranch: {\n title: 'Default Branch',\n type: 'string',\n description: `Sets the default branch on the repository. The default value is 'master'`,\n },\n sourcePath: {\n title: 'Source Path',\n description:\n 'Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.',\n type: 'string',\n },\n enableLFS: {\n title: 'Enable LFS?',\n description: 'Enable LFS for the repository.',\n type: 'boolean',\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description:\n 'The token to use for authorization to BitBucket Server',\n },\n gitCommitMessage: {\n title: 'Git Commit Message',\n type: 'string',\n description: `Sets the commit message on the repository. The default value is 'initial commit'`,\n },\n gitAuthorName: {\n title: 'Author Name',\n type: 'string',\n description: `Sets the author name for the commit. The default value is 'Scaffolder'`,\n },\n gitAuthorEmail: {\n title: 'Author Email',\n type: 'string',\n description: `Sets the author email for the commit.`,\n },\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: {\n title: 'A URL to the repository with the provider',\n type: 'string',\n },\n repoContentsUrl: {\n title: 'A URL to the root of the repository',\n type: 'string',\n },\n commitHash: {\n title: 'The git commit hash of the initial commit',\n type: 'string',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n description,\n defaultBranch = 'master',\n repoVisibility = 'private',\n enableLFS = false,\n gitCommitMessage = 'initial commit',\n gitAuthorName,\n gitAuthorEmail,\n } = ctx.input;\n\n const { project, repo, host } = parseRepoUrl(repoUrl, integrations);\n\n if (!project) {\n throw new InputError(\n `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`,\n );\n }\n\n const integrationConfig = integrations.bitbucketServer.byHost(host);\n if (!integrationConfig) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n const token = ctx.input.token ?? integrationConfig.config.token;\n\n const authConfig = {\n ...integrationConfig.config,\n ...{ token },\n };\n const reqOpts = getBitbucketServerRequestOptions(authConfig);\n const authorization = reqOpts.headers.Authorization;\n if (!authorization) {\n throw new Error(\n `Authorization has not been provided for ${integrationConfig.config.host}. Please add either (a) a user login auth token, or (b) a token or (c) username + password to the integration config.`,\n );\n }\n\n const apiBaseUrl = integrationConfig.config.apiBaseUrl;\n\n const { remoteUrl, repoContentsUrl } = await createRepository({\n authorization,\n project,\n repo,\n repoVisibility,\n defaultBranch,\n description,\n apiBaseUrl,\n });\n\n const gitAuthorInfo = {\n name: gitAuthorName\n ? gitAuthorName\n : config.getOptionalString('scaffolder.defaultAuthor.name'),\n email: gitAuthorEmail\n ? gitAuthorEmail\n : config.getOptionalString('scaffolder.defaultAuthor.email'),\n };\n\n const auth = authConfig.token\n ? {\n token: token!,\n }\n : {\n username: authConfig.username!,\n password: authConfig.password!,\n };\n\n const commitResult = await initRepoAndPush({\n dir: getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),\n remoteUrl,\n auth,\n defaultBranch,\n logger: ctx.logger,\n commitMessage: gitCommitMessage\n ? gitCommitMessage\n : config.getOptionalString('scaffolder.defaultCommitMessage'),\n gitAuthorInfo,\n });\n\n if (enableLFS) {\n await performEnableLFS({ authorization, host, project, repo });\n }\n\n ctx.output('commitHash', commitResult?.commitHash);\n ctx.output('remoteUrl', remoteUrl);\n ctx.output('repoContentsUrl', repoContentsUrl);\n },\n });\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport crypto from 'crypto';\nimport { InputError } from '@backstage/errors';\nimport { Config } from '@backstage/config';\nimport {\n GerritIntegrationConfig,\n getGerritRequestOptions,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { getRepoSourceDirectory, parseRepoUrl } from './util';\nimport fetch, { Response, RequestInit } from 'node-fetch';\nimport { initRepoAndPush } from '../helpers';\n\nconst createGerritProject = async (\n config: GerritIntegrationConfig,\n options: {\n projectName: string;\n parent: string;\n owner?: string;\n description: string;\n },\n): Promise<void> => {\n const { projectName, parent, owner, description } = options;\n\n const fetchOptions: RequestInit = {\n method: 'PUT',\n body: JSON.stringify({\n parent,\n description,\n owners: owner ? [owner] : [],\n create_empty_commit: false,\n }),\n headers: {\n ...getGerritRequestOptions(config).headers,\n 'Content-Type': 'application/json',\n },\n };\n const response: Response = await fetch(\n `${config.baseUrl}/a/projects/${encodeURIComponent(projectName)}`,\n fetchOptions,\n );\n if (response.status !== 201) {\n throw new Error(\n `Unable to create repository, ${response.status} ${\n response.statusText\n }, ${await response.text()}`,\n );\n }\n};\n\nconst generateCommitMessage = (\n config: Config,\n commitSubject?: string,\n): string => {\n const changeId = crypto.randomBytes(20).toString('hex');\n const msg = `${\n config.getOptionalString('scaffolder.defaultCommitMessage') || commitSubject\n }\\n\\nChange-Id: I${changeId}`;\n return msg;\n};\n\n/**\n * Creates a new action that initializes a git repository of the content in the workspace\n * and publishes it to a Gerrit instance.\n * @public\n */\nexport function createPublishGerritAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n}) {\n const { integrations, config } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n description: string;\n defaultBranch?: string;\n gitCommitMessage?: string;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n sourcePath?: string;\n }>({\n id: 'publish:gerrit',\n description:\n 'Initializes a git repository of the content in the workspace, and publishes it to Gerrit.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n type: 'string',\n },\n description: {\n title: 'Repository Description',\n type: 'string',\n },\n defaultBranch: {\n title: 'Default Branch',\n type: 'string',\n description: `Sets the default branch on the repository. The default value is 'master'`,\n },\n gitCommitMessage: {\n title: 'Git Commit Message',\n type: 'string',\n description: `Sets the commit message on the repository. The default value is 'initial commit'`,\n },\n gitAuthorName: {\n title: 'Default Author Name',\n type: 'string',\n description: `Sets the default author name for the commit. The default value is 'Scaffolder'`,\n },\n gitAuthorEmail: {\n title: 'Default Author Email',\n type: 'string',\n description: `Sets the default author email for the commit.`,\n },\n sourcePath: {\n title: 'Source Path',\n type: 'string',\n description: `Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.`,\n },\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: {\n title: 'A URL to the repository with the provider',\n type: 'string',\n },\n repoContentsUrl: {\n title: 'A URL to the root of the repository',\n type: 'string',\n },\n commitHash: {\n title: 'The git commit hash of the initial commit',\n type: 'string',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n description,\n defaultBranch = 'master',\n gitAuthorName,\n gitAuthorEmail,\n gitCommitMessage = 'initial commit',\n sourcePath,\n } = ctx.input;\n const { repo, host, owner, workspace } = parseRepoUrl(\n repoUrl,\n integrations,\n );\n\n const integrationConfig = integrations.gerrit.byHost(host);\n\n if (!integrationConfig) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n if (!workspace) {\n throw new InputError(\n `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`,\n );\n }\n\n await createGerritProject(integrationConfig.config, {\n description,\n owner: owner,\n projectName: repo,\n parent: workspace,\n });\n const auth = {\n username: integrationConfig.config.username!,\n password: integrationConfig.config.password!,\n };\n const gitAuthorInfo = {\n name: gitAuthorName\n ? gitAuthorName\n : config.getOptionalString('scaffolder.defaultAuthor.name'),\n email: gitAuthorEmail\n ? gitAuthorEmail\n : config.getOptionalString('scaffolder.defaultAuthor.email'),\n };\n\n const remoteUrl = `${integrationConfig.config.cloneUrl}/a/${repo}`;\n const commitResult = await initRepoAndPush({\n dir: getRepoSourceDirectory(ctx.workspacePath, sourcePath),\n remoteUrl,\n auth,\n defaultBranch,\n logger: ctx.logger,\n commitMessage: generateCommitMessage(config, gitCommitMessage),\n gitAuthorInfo,\n });\n\n const repoContentsUrl = `${integrationConfig.config.gitilesBaseUrl}/${repo}/+/refs/heads/${defaultBranch}`;\n ctx.output('remoteUrl', remoteUrl);\n ctx.output('commitHash', commitResult?.commitHash);\n ctx.output('repoContentsUrl', repoContentsUrl);\n },\n });\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport crypto from 'crypto';\nimport { InputError } from '@backstage/errors';\nimport { Config } from '@backstage/config';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { getRepoSourceDirectory, parseRepoUrl } from './util';\nimport { commitAndPushRepo } from '../helpers';\n\nconst generateGerritChangeId = (): string => {\n const changeId = crypto.randomBytes(20).toString('hex');\n return `I${changeId}`;\n};\n\n/**\n * Creates a new action that creates a Gerrit review\n * @public\n */\nexport function createPublishGerritReviewAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n}) {\n const { integrations, config } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n branch?: string;\n sourcePath?: string;\n gitCommitMessage?: string;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n }>({\n id: 'publish:gerrit:review',\n description: 'Creates a new Gerrit review.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl', 'gitCommitMessage'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n type: 'string',\n },\n branch: {\n title: 'Repository branch',\n type: 'string',\n description:\n 'Branch of the repository the review will be created on',\n },\n sourcePath: {\n type: 'string',\n title: 'Working Subdirectory',\n description:\n 'Subdirectory of working directory containing the repository',\n },\n gitCommitMessage: {\n title: 'Git Commit Message',\n type: 'string',\n description: `Sets the commit message on the repository.`,\n },\n gitAuthorName: {\n title: 'Default Author Name',\n type: 'string',\n description: `Sets the default author name for the commit. The default value is 'Scaffolder'`,\n },\n gitAuthorEmail: {\n title: 'Default Author Email',\n type: 'string',\n description: `Sets the default author email for the commit.`,\n },\n },\n },\n output: {\n type: 'object',\n properties: {\n reviewUrl: {\n title: 'A URL to the review',\n type: 'string',\n },\n repoContentsUrl: {\n title: 'A URL to the root of the repository',\n type: 'string',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n branch = 'master',\n sourcePath,\n gitAuthorName,\n gitAuthorEmail,\n gitCommitMessage,\n } = ctx.input;\n const { host, repo } = parseRepoUrl(repoUrl, integrations);\n\n if (!gitCommitMessage) {\n throw new InputError(`Missing gitCommitMessage input`);\n }\n\n const integrationConfig = integrations.gerrit.byHost(host);\n\n if (!integrationConfig) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n const auth = {\n username: integrationConfig.config.username!,\n password: integrationConfig.config.password!,\n };\n const gitAuthorInfo = {\n name: gitAuthorName\n ? gitAuthorName\n : config.getOptionalString('scaffolder.defaultAuthor.name'),\n email: gitAuthorEmail\n ? gitAuthorEmail\n : config.getOptionalString('scaffolder.defaultAuthor.email'),\n };\n const changeId = generateGerritChangeId();\n const commitMessage = `${gitCommitMessage}\\n\\nChange-Id: ${changeId}`;\n\n await commitAndPushRepo({\n dir: getRepoSourceDirectory(ctx.workspacePath, sourcePath),\n auth,\n logger: ctx.logger,\n commitMessage,\n gitAuthorInfo,\n branch,\n remoteRef: `refs/for/${branch}`,\n });\n\n const repoContentsUrl = `${integrationConfig.config.gitilesBaseUrl}/${repo}/+/refs/heads/${branch}`;\n const reviewUrl = `${integrationConfig.config.baseUrl}/#/q/${changeId}`;\n ctx.logger?.info(`Review available on ${reviewUrl}`);\n ctx.output('repoContentsUrl', repoContentsUrl);\n ctx.output('reviewUrl', reviewUrl);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { InputError } from '@backstage/errors';\nimport {\n GithubCredentialsProvider,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { Octokit } from 'octokit';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport {\n createGithubRepoWithCollaboratorsAndTopics,\n getOctokitOptions,\n initRepoPushAndProtect,\n} from '../github/helpers';\nimport * as inputProps from '../github/inputProperties';\nimport * as outputProps from '../github/outputProperties';\nimport { parseRepoUrl } from './util';\n\n/**\n * Creates a new action that initializes a git repository of the content in the workspace\n * and publishes it to GitHub.\n *\n * @public\n */\nexport function createPublishGithubAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n githubCredentialsProvider?: GithubCredentialsProvider;\n}) {\n const { integrations, config, githubCredentialsProvider } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n description?: string;\n homepage?: string;\n access?: string;\n defaultBranch?: string;\n protectDefaultBranch?: boolean;\n protectEnforceAdmins?: boolean;\n deleteBranchOnMerge?: boolean;\n gitCommitMessage?: string;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n allowRebaseMerge?: boolean;\n allowSquashMerge?: boolean;\n squashMergeCommitTitle?: 'PR_TITLE' | 'COMMIT_OR_PR_TITLE';\n squashMergeCommitMessage?: 'PR_BODY' | 'COMMIT_MESSAGES' | 'BLANK';\n allowMergeCommit?: boolean;\n allowAutoMerge?: boolean;\n sourcePath?: string;\n bypassPullRequestAllowances?:\n | {\n users?: string[];\n teams?: string[];\n apps?: string[];\n }\n | undefined;\n requiredApprovingReviewCount?: number;\n restrictions?:\n | {\n users: string[];\n teams: string[];\n apps?: string[];\n }\n | undefined;\n requireCodeOwnerReviews?: boolean;\n dismissStaleReviews?: boolean;\n requiredStatusCheckContexts?: string[];\n requireBranchesToBeUpToDate?: boolean;\n requiredConversationResolution?: boolean;\n repoVisibility?: 'private' | 'internal' | 'public';\n collaborators?: Array<\n | {\n user: string;\n access: string;\n }\n | {\n team: string;\n access: string;\n }\n | {\n /** @deprecated This field is deprecated in favor of team */\n username: string;\n access: 'pull' | 'push' | 'admin' | 'maintain' | 'triage';\n }\n >;\n hasProjects?: boolean | undefined;\n hasWiki?: boolean | undefined;\n hasIssues?: boolean | undefined;\n token?: string;\n topics?: string[];\n repoVariables?: { [key: string]: string };\n secrets?: { [key: string]: string };\n requiredCommitSigning?: boolean;\n }>({\n id: 'publish:github',\n description:\n 'Initializes a git repository of contents in workspace and publishes it to GitHub.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: inputProps.repoUrl,\n description: inputProps.description,\n homepage: inputProps.homepage,\n access: inputProps.access,\n bypassPullRequestAllowances: inputProps.bypassPullRequestAllowances,\n requiredApprovingReviewCount: inputProps.requiredApprovingReviewCount,\n restrictions: inputProps.restrictions,\n requireCodeOwnerReviews: inputProps.requireCodeOwnerReviews,\n dismissStaleReviews: inputProps.dismissStaleReviews,\n requiredStatusCheckContexts: inputProps.requiredStatusCheckContexts,\n requireBranchesToBeUpToDate: inputProps.requireBranchesToBeUpToDate,\n requiredConversationResolution:\n inputProps.requiredConversationResolution,\n repoVisibility: inputProps.repoVisibility,\n defaultBranch: inputProps.defaultBranch,\n protectDefaultBranch: inputProps.protectDefaultBranch,\n protectEnforceAdmins: inputProps.protectEnforceAdmins,\n deleteBranchOnMerge: inputProps.deleteBranchOnMerge,\n gitCommitMessage: inputProps.gitCommitMessage,\n gitAuthorName: inputProps.gitAuthorName,\n gitAuthorEmail: inputProps.gitAuthorEmail,\n allowMergeCommit: inputProps.allowMergeCommit,\n allowSquashMerge: inputProps.allowSquashMerge,\n squashMergeCommitTitle: inputProps.squashMergeCommitTitle,\n squashMergeCommitMessage: inputProps.squashMergeCommitMessage,\n allowRebaseMerge: inputProps.allowRebaseMerge,\n allowAutoMerge: inputProps.allowAutoMerge,\n sourcePath: inputProps.sourcePath,\n collaborators: inputProps.collaborators,\n hasProjects: inputProps.hasProjects,\n hasWiki: inputProps.hasWiki,\n hasIssues: inputProps.hasIssues,\n token: inputProps.token,\n topics: inputProps.topics,\n repoVariables: inputProps.repoVariables,\n secrets: inputProps.secrets,\n requiredCommitSigning: inputProps.requiredCommitSigning,\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: outputProps.remoteUrl,\n repoContentsUrl: outputProps.repoContentsUrl,\n commitHash: outputProps.commitHash,\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n description,\n homepage,\n access,\n requireCodeOwnerReviews = false,\n dismissStaleReviews = false,\n bypassPullRequestAllowances,\n requiredApprovingReviewCount = 1,\n restrictions,\n requiredStatusCheckContexts = [],\n requireBranchesToBeUpToDate = true,\n requiredConversationResolution = false,\n repoVisibility = 'private',\n defaultBranch = 'master',\n protectDefaultBranch = true,\n protectEnforceAdmins = true,\n deleteBranchOnMerge = false,\n gitCommitMessage = 'initial commit',\n gitAuthorName,\n gitAuthorEmail,\n allowMergeCommit = true,\n allowSquashMerge = true,\n squashMergeCommitTitle = 'COMMIT_OR_PR_TITLE',\n squashMergeCommitMessage = 'COMMIT_MESSAGES',\n allowRebaseMerge = true,\n allowAutoMerge = false,\n collaborators,\n hasProjects = undefined,\n hasWiki = undefined,\n hasIssues = undefined,\n topics,\n repoVariables,\n secrets,\n token: providedToken,\n requiredCommitSigning = false,\n } = ctx.input;\n\n const octokitOptions = await getOctokitOptions({\n integrations,\n credentialsProvider: githubCredentialsProvider,\n token: providedToken,\n repoUrl: repoUrl,\n });\n const client = new Octokit(octokitOptions);\n\n const { owner, repo } = parseRepoUrl(repoUrl, integrations);\n\n if (!owner) {\n throw new InputError('Invalid repository owner provided in repoUrl');\n }\n\n const newRepo = await createGithubRepoWithCollaboratorsAndTopics(\n client,\n repo,\n owner,\n repoVisibility,\n description,\n homepage,\n deleteBranchOnMerge,\n allowMergeCommit,\n allowSquashMerge,\n squashMergeCommitTitle,\n squashMergeCommitMessage,\n allowRebaseMerge,\n allowAutoMerge,\n access,\n collaborators,\n hasProjects,\n hasWiki,\n hasIssues,\n topics,\n repoVariables,\n secrets,\n ctx.logger,\n );\n\n const remoteUrl = newRepo.clone_url;\n const repoContentsUrl = `${newRepo.html_url}/blob/${defaultBranch}`;\n\n const commitResult = await initRepoPushAndProtect(\n remoteUrl,\n octokitOptions.auth,\n ctx.workspacePath,\n ctx.input.sourcePath,\n defaultBranch,\n protectDefaultBranch,\n protectEnforceAdmins,\n owner,\n client,\n repo,\n requireCodeOwnerReviews,\n bypassPullRequestAllowances,\n requiredApprovingReviewCount,\n restrictions,\n requiredStatusCheckContexts,\n requireBranchesToBeUpToDate,\n requiredConversationResolution,\n config,\n ctx.logger,\n gitCommitMessage,\n gitAuthorName,\n gitAuthorEmail,\n dismissStaleReviews,\n requiredCommitSigning,\n );\n\n ctx.output('commitHash', commitResult?.commitHash);\n ctx.output('remoteUrl', remoteUrl);\n ctx.output('repoContentsUrl', repoContentsUrl);\n },\n });\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { promises as fs } from 'fs';\nimport globby from 'globby';\nimport limiterFactory from 'p-limit';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\nimport { SerializedFile } from './types';\nimport { isError } from '@backstage/errors';\n\nconst DEFAULT_GLOB_PATTERNS = ['./**', '!.git'];\n\nexport const isExecutable = (fileMode: number | undefined) => {\n if (!fileMode) {\n return false;\n }\n\n const executeBitMask = 0o000111;\n const res = fileMode & executeBitMask;\n return res > 0;\n};\n\nasync function asyncFilter<T>(\n array: T[],\n callback: (value: T, index: number, array: T[]) => Promise<boolean>,\n): Promise<T[]> {\n const filterMap = await Promise.all(array.map(callback));\n return array.filter((_value, index) => filterMap[index]);\n}\n\nexport async function serializeDirectoryContents(\n sourcePath: string,\n options?: {\n gitignore?: boolean;\n globPatterns?: string[];\n },\n): Promise<SerializedFile[]> {\n const paths = await globby(options?.globPatterns ?? DEFAULT_GLOB_PATTERNS, {\n cwd: sourcePath,\n dot: true,\n gitignore: options?.gitignore,\n followSymbolicLinks: false,\n // In order to pick up 'broken' symlinks, we oxymoronically request files AND folders yet we filter out folders\n // This is because broken symlinks aren't classed as files so we need to glob everything\n onlyFiles: false,\n objectMode: true,\n stats: true,\n });\n\n const limiter = limiterFactory(10);\n\n const valid = await asyncFilter(paths, async ({ dirent, path }) => {\n if (dirent.isDirectory()) return false;\n if (!dirent.isSymbolicLink()) return true;\n\n const safePath = resolveSafeChildPath(sourcePath, path);\n\n // we only want files that don't exist\n try {\n await fs.stat(safePath);\n return false;\n } catch (e) {\n return isError(e) && e.code === 'ENOENT';\n }\n });\n\n return Promise.all(\n valid.map(async ({ dirent, path, stats }) => ({\n path,\n content: await limiter(async () => {\n const absFilePath = resolveSafeChildPath(sourcePath, path);\n if (dirent.isSymbolicLink()) {\n return fs.readlink(absFilePath, 'buffer');\n }\n return fs.readFile(absFilePath);\n }),\n executable: isExecutable(stats?.mode),\n symlink: dirent.isSymbolicLink(),\n })),\n );\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { dirname } from 'path';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\nimport { SerializedFile } from './types';\n\n/**\n * Deserializes a list of serialized files into the target directory.\n *\n * This method uses `resolveSafeChildPath` to make sure that files are\n * not written outside of the target directory.\n *\n * @internal\n */\nexport async function deserializeDirectoryContents(\n targetPath: string,\n files: SerializedFile[],\n): Promise<void> {\n for (const file of files) {\n const filePath = resolveSafeChildPath(targetPath, file.path);\n await fs.ensureDir(dirname(filePath));\n await fs.writeFile(filePath, file.content); // Ignore file mode\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport path from 'path';\nimport { parseRepoUrl } from './util';\nimport {\n GithubCredentialsProvider,\n ScmIntegrationRegistry,\n} from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { Octokit } from 'octokit';\nimport { InputError, CustomErrorBase } from '@backstage/errors';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\nimport { createPullRequest } from 'octokit-plugin-create-pull-request';\nimport { getOctokitOptions } from '../github/helpers';\nimport {\n SerializedFile,\n serializeDirectoryContents,\n} from '../../../../lib/files';\nimport { Logger } from 'winston';\n\nexport type Encoding = 'utf-8' | 'base64';\n\nclass GithubResponseError extends CustomErrorBase {}\n\n/** @public */\nexport type OctokitWithPullRequestPluginClient = Octokit & {\n createPullRequest(options: createPullRequest.Options): Promise<{\n data: {\n html_url: string;\n number: number;\n };\n } | null>;\n};\n\n/**\n * The options passed to the client factory function.\n * @public\n */\nexport type CreateGithubPullRequestClientFactoryInput = {\n integrations: ScmIntegrationRegistry;\n githubCredentialsProvider?: GithubCredentialsProvider;\n host: string;\n owner: string;\n repo: string;\n token?: string;\n};\n\nexport const defaultClientFactory = async ({\n integrations,\n githubCredentialsProvider,\n owner,\n repo,\n host = 'github.com',\n token: providedToken,\n}: CreateGithubPullRequestClientFactoryInput): Promise<OctokitWithPullRequestPluginClient> => {\n const [encodedHost, encodedOwner, encodedRepo] = [host, owner, repo].map(\n encodeURIComponent,\n );\n\n const octokitOptions = await getOctokitOptions({\n integrations,\n credentialsProvider: githubCredentialsProvider,\n repoUrl: `${encodedHost}?owner=${encodedOwner}&repo=${encodedRepo}`,\n token: providedToken,\n });\n\n const OctokitPR = Octokit.plugin(createPullRequest);\n return new OctokitPR({\n ...octokitOptions,\n ...{ throttle: { enabled: false } },\n });\n};\n\n/**\n * The options passed to {@link createPublishGithubPullRequestAction} method\n * @public\n */\nexport interface CreateGithubPullRequestActionOptions {\n /**\n * An instance of {@link @backstage/integration#ScmIntegrationRegistry} that will be used in the action.\n */\n integrations: ScmIntegrationRegistry;\n /**\n * An instance of {@link @backstage/integration#GithubCredentialsProvider} that will be used to get credentials for the action.\n */\n githubCredentialsProvider?: GithubCredentialsProvider;\n /**\n * A method to return the Octokit client with the Pull Request Plugin.\n */\n clientFactory?: (\n input: CreateGithubPullRequestClientFactoryInput,\n ) => Promise<OctokitWithPullRequestPluginClient>;\n}\n\ntype GithubPullRequest = {\n owner: string;\n repo: string;\n number: number;\n};\n\n/**\n * Creates a Github Pull Request action.\n * @public\n */\nexport const createPublishGithubPullRequestAction = (\n options: CreateGithubPullRequestActionOptions,\n) => {\n const {\n integrations,\n githubCredentialsProvider,\n clientFactory = defaultClientFactory,\n } = options;\n\n return createTemplateAction<{\n title: string;\n branchName: string;\n description: string;\n repoUrl: string;\n draft?: boolean;\n targetPath?: string;\n sourcePath?: string;\n token?: string;\n reviewers?: string[];\n teamReviewers?: string[];\n commitMessage?: string;\n }>({\n id: 'publish:github:pull-request',\n schema: {\n input: {\n required: ['repoUrl', 'title', 'description', 'branchName'],\n type: 'object',\n properties: {\n repoUrl: {\n title: 'Repository Location',\n description: `Accepts the format 'github.com?repo=reponame&owner=owner' where 'reponame' is the repository name and 'owner' is an organization or username`,\n type: 'string',\n },\n branchName: {\n type: 'string',\n title: 'Branch Name',\n description: 'The name for the branch',\n },\n title: {\n type: 'string',\n title: 'Pull Request Name',\n description: 'The name for the pull request',\n },\n description: {\n type: 'string',\n title: 'Pull Request Description',\n description: 'The description of the pull request',\n },\n draft: {\n type: 'boolean',\n title: 'Create as Draft',\n description: 'Create a draft pull request',\n },\n sourcePath: {\n type: 'string',\n title: 'Working Subdirectory',\n description:\n 'Subdirectory of working directory to copy changes from',\n },\n targetPath: {\n type: 'string',\n title: 'Repository Subdirectory',\n description: 'Subdirectory of repository to apply changes to',\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description: 'The token to use for authorization to GitHub',\n },\n reviewers: {\n title: 'Pull Request Reviewers',\n type: 'array',\n items: {\n type: 'string',\n },\n description:\n 'The users that will be added as reviewers to the pull request',\n },\n teamReviewers: {\n title: 'Pull Request Team Reviewers',\n type: 'array',\n items: {\n type: 'string',\n },\n description:\n 'The teams that will be added as reviewers to the pull request',\n },\n commitMessage: {\n type: 'string',\n title: 'Commit Message',\n description: 'The commit message for the pull request commit',\n },\n },\n },\n output: {\n required: ['remoteUrl'],\n type: 'object',\n properties: {\n remoteUrl: {\n type: 'string',\n title: 'Pull Request URL',\n description: 'Link to the pull request in Github',\n },\n pullRequestNumber: {\n type: 'number',\n title: 'Pull Request Number',\n description: 'The pull request number',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n branchName,\n title,\n description,\n draft,\n targetPath,\n sourcePath,\n token: providedToken,\n reviewers,\n teamReviewers,\n commitMessage,\n } = ctx.input;\n\n const { owner, repo, host } = parseRepoUrl(repoUrl, integrations);\n\n if (!owner) {\n throw new InputError(\n `No owner provided for host: ${host}, and repo ${repo}`,\n );\n }\n\n const client = await clientFactory({\n integrations,\n githubCredentialsProvider,\n host,\n owner,\n repo,\n token: providedToken,\n });\n\n const fileRoot = sourcePath\n ? resolveSafeChildPath(ctx.workspacePath, sourcePath)\n : ctx.workspacePath;\n\n const directoryContents = await serializeDirectoryContents(fileRoot, {\n gitignore: true,\n });\n\n const determineFileMode = (file: SerializedFile): string => {\n if (file.symlink) return '120000';\n if (file.executable) return '100755';\n return '100644';\n };\n\n const determineFileEncoding = (\n file: SerializedFile,\n ): 'utf-8' | 'base64' => (file.symlink ? 'utf-8' : 'base64');\n\n const files = Object.fromEntries(\n directoryContents.map(file => [\n targetPath ? path.posix.join(targetPath, file.path) : file.path,\n {\n // See the properties of tree items\n // in https://docs.github.com/en/rest/reference/git#trees\n mode: determineFileMode(file),\n // Always use base64 encoding where possible to avoid doubling a binary file in size\n // due to interpreting a binary file as utf-8 and sending github\n // the utf-8 encoded content. Symlinks are kept as utf-8 to avoid them\n // being formatted as a series of scrambled characters\n //\n // For example, the original gradle-wrapper.jar is 57.8k in https://github.com/kennethzfeng/pull-request-test/pull/5/files.\n // Its size could be doubled to 98.3K (See https://github.com/kennethzfeng/pull-request-test/pull/4/files)\n encoding: determineFileEncoding(file),\n content: file.content.toString(determineFileEncoding(file)),\n },\n ]),\n );\n\n try {\n const response = await client.createPullRequest({\n owner,\n repo,\n title,\n changes: [\n {\n files,\n commit: commitMessage ?? title,\n },\n ],\n body: description,\n head: branchName,\n draft,\n });\n\n if (!response) {\n throw new GithubResponseError('null response from Github');\n }\n\n const pullRequestNumber = response.data.number;\n if (reviewers || teamReviewers) {\n const pullRequest = { owner, repo, number: pullRequestNumber };\n await requestReviewersOnPullRequest(\n pullRequest,\n reviewers,\n teamReviewers,\n client,\n ctx.logger,\n );\n }\n\n ctx.output('remoteUrl', response.data.html_url);\n ctx.output('pullRequestNumber', pullRequestNumber);\n } catch (e) {\n throw new GithubResponseError('Pull request creation failed', e);\n }\n },\n });\n\n async function requestReviewersOnPullRequest(\n pr: GithubPullRequest,\n reviewers: string[] | undefined,\n teamReviewers: string[] | undefined,\n client: Octokit,\n logger: Logger,\n ) {\n try {\n const result = await client.rest.pulls.requestReviewers({\n owner: pr.owner,\n repo: pr.repo,\n pull_number: pr.number,\n reviewers,\n team_reviewers: teamReviewers,\n });\n const addedUsers = result.data.requested_reviewers?.join(', ') ?? '';\n const addedTeams = result.data.requested_teams?.join(', ') ?? '';\n logger.info(\n `Added users [${addedUsers}] and teams [${addedTeams}] as reviewers to Pull request ${pr.number}`,\n );\n } catch (e) {\n logger.error(\n `Failure when adding reviewers to Pull request ${pr.number}`,\n e,\n );\n }\n }\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InputError } from '@backstage/errors';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { Gitlab } from '@gitbeaker/node';\nimport { initRepoAndPush } from '../helpers';\nimport { getRepoSourceDirectory, parseRepoUrl } from './util';\nimport { Config } from '@backstage/config';\n\n/**\n * Creates a new action that initializes a git repository of the content in the workspace\n * and publishes it to GitLab.\n *\n * @public\n */\nexport function createPublishGitlabAction(options: {\n integrations: ScmIntegrationRegistry;\n config: Config;\n}) {\n const { integrations, config } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n defaultBranch?: string;\n repoVisibility?: 'private' | 'internal' | 'public';\n sourcePath?: string;\n token?: string;\n gitCommitMessage?: string;\n gitAuthorName?: string;\n gitAuthorEmail?: string;\n setUserAsOwner?: boolean;\n topics?: string[];\n }>({\n id: 'publish:gitlab',\n description:\n 'Initializes a git repository of the content in the workspace, and publishes it to GitLab.',\n schema: {\n input: {\n type: 'object',\n required: ['repoUrl'],\n properties: {\n repoUrl: {\n title: 'Repository Location',\n type: 'string',\n description: `Accepts the format 'gitlab.com?repo=project_name&owner=group_name' where 'project_name' is the repository name and 'group_name' is a group or username`,\n },\n repoVisibility: {\n title: 'Repository Visibility',\n type: 'string',\n enum: ['private', 'public', 'internal'],\n },\n defaultBranch: {\n title: 'Default Branch',\n type: 'string',\n description: `Sets the default branch on the repository. The default value is 'master'`,\n },\n gitCommitMessage: {\n title: 'Git Commit Message',\n type: 'string',\n description: `Sets the commit message on the repository. The default value is 'initial commit'`,\n },\n gitAuthorName: {\n title: 'Default Author Name',\n type: 'string',\n description: `Sets the default author name for the commit. The default value is 'Scaffolder'`,\n },\n gitAuthorEmail: {\n title: 'Default Author Email',\n type: 'string',\n description: `Sets the default author email for the commit.`,\n },\n sourcePath: {\n title: 'Source Path',\n description:\n 'Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.',\n type: 'string',\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description: 'The token to use for authorization to GitLab',\n },\n setUserAsOwner: {\n title: 'Set User As Owner',\n type: 'boolean',\n description:\n 'Set the token user as owner of the newly created repository. Requires a token authorized to do the edit in the integration configuration for the matching host',\n },\n topics: {\n title: 'Topic labels',\n description: 'Topic labels to apply on the repository.',\n type: 'array',\n items: {\n type: 'string',\n },\n },\n },\n },\n output: {\n type: 'object',\n properties: {\n remoteUrl: {\n title: 'A URL to the repository with the provider',\n type: 'string',\n },\n repoContentsUrl: {\n title: 'A URL to the root of the repository',\n type: 'string',\n },\n projectId: {\n title: 'The ID of the project',\n type: 'string',\n },\n commitHash: {\n title: 'The git commit hash of the initial commit',\n type: 'string',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n repoUrl,\n repoVisibility = 'private',\n defaultBranch = 'master',\n gitCommitMessage = 'initial commit',\n gitAuthorName,\n gitAuthorEmail,\n setUserAsOwner = false,\n topics = [],\n } = ctx.input;\n const { owner, repo, host } = parseRepoUrl(repoUrl, integrations);\n\n if (!owner) {\n throw new InputError(\n `No owner provided for host: ${host}, and repo ${repo}`,\n );\n }\n\n const integrationConfig = integrations.gitlab.byHost(host);\n\n if (!integrationConfig) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n if (!integrationConfig.config.token && !ctx.input.token) {\n throw new InputError(`No token available for host ${host}`);\n }\n\n const token = ctx.input.token || integrationConfig.config.token!;\n const tokenType = ctx.input.token ? 'oauthToken' : 'token';\n\n const client = new Gitlab({\n host: integrationConfig.config.baseUrl,\n [tokenType]: token,\n });\n\n let { id: targetNamespace } = (await client.Namespaces.show(owner)) as {\n id: number;\n };\n\n const { id: userId } = (await client.Users.current()) as {\n id: number;\n };\n\n if (!targetNamespace) {\n targetNamespace = userId;\n }\n\n const { id: projectId, http_url_to_repo } = await client.Projects.create({\n namespace_id: targetNamespace,\n name: repo,\n visibility: repoVisibility,\n ...(topics.length ? { topics } : {}),\n });\n\n // When setUserAsOwner is true the input token is expected to come from an unprivileged user GitLab\n // OAuth flow. In this case GitLab works in a way that allows the unprivileged user to\n // create the repository, but not to push the default protected branch (e.g. master).\n // In order to set the user as owner of the newly created repository we need to check that the\n // GitLab integration configuration for the matching host contains a token and use\n // such token to bootstrap a new privileged client.\n if (setUserAsOwner && integrationConfig.config.token) {\n const adminClient = new Gitlab({\n host: integrationConfig.config.baseUrl,\n token: integrationConfig.config.token,\n });\n\n await adminClient.ProjectMembers.add(projectId, userId, 50);\n }\n\n const remoteUrl = (http_url_to_repo as string).replace(/\\.git$/, '');\n const repoContentsUrl = `${remoteUrl}/-/blob/${defaultBranch}`;\n\n const gitAuthorInfo = {\n name: gitAuthorName\n ? gitAuthorName\n : config.getOptionalString('scaffolder.defaultAuthor.name'),\n email: gitAuthorEmail\n ? gitAuthorEmail\n : config.getOptionalString('scaffolder.defaultAuthor.email'),\n };\n const commitResult = await initRepoAndPush({\n dir: getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),\n remoteUrl: http_url_to_repo as string,\n defaultBranch,\n auth: {\n username: 'oauth2',\n password: token,\n },\n logger: ctx.logger,\n commitMessage: gitCommitMessage\n ? gitCommitMessage\n : config.getOptionalString('scaffolder.defaultCommitMessage'),\n gitAuthorInfo,\n });\n\n ctx.output('commitHash', commitResult?.commitHash);\n ctx.output('remoteUrl', remoteUrl);\n ctx.output('repoContentsUrl', repoContentsUrl);\n ctx.output('projectId', projectId);\n },\n });\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createTemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { Gitlab } from '@gitbeaker/node';\nimport { Types } from '@gitbeaker/core';\nimport path from 'path';\nimport { ScmIntegrationRegistry } from '@backstage/integration';\nimport { InputError } from '@backstage/errors';\nimport { parseRepoUrl } from './util';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\nimport { serializeDirectoryContents } from '../../../../lib/files';\n\n/**\n * Create a new action that creates a gitlab merge request.\n *\n * @public\n */\nexport const createPublishGitlabMergeRequestAction = (options: {\n integrations: ScmIntegrationRegistry;\n}) => {\n const { integrations } = options;\n\n return createTemplateAction<{\n repoUrl: string;\n title: string;\n description: string;\n branchName: string;\n sourcePath?: string;\n targetPath?: string;\n token?: string;\n commitAction?: 'create' | 'delete' | 'update';\n /** @deprecated projectID passed as query parameters in the repoUrl */\n projectid?: string;\n removeSourceBranch?: boolean;\n assignee?: string;\n }>({\n id: 'publish:gitlab:merge-request',\n schema: {\n input: {\n required: ['repoUrl', 'branchName'],\n type: 'object',\n properties: {\n repoUrl: {\n type: 'string',\n title: 'Repository Location',\n description: `Accepts the format 'gitlab.com?repo=project_name&owner=group_name' where 'project_name' is the repository name and 'group_name' is a group or username`,\n },\n /** @deprecated projectID is passed as query parameters in the repoUrl */\n projectid: {\n type: 'string',\n title: 'projectid',\n description: 'Project ID/Name(slug) of the Gitlab Project',\n },\n title: {\n type: 'string',\n title: 'Merge Request Name',\n description: 'The name for the merge request',\n },\n description: {\n type: 'string',\n title: 'Merge Request Description',\n description: 'The description of the merge request',\n },\n branchName: {\n type: 'string',\n title: 'Destination Branch name',\n description: 'The description of the merge request',\n },\n sourcePath: {\n type: 'string',\n title: 'Working Subdirectory',\n description:\n 'Subdirectory of working directory to copy changes from',\n },\n targetPath: {\n type: 'string',\n title: 'Repository Subdirectory',\n description: 'Subdirectory of repository to apply changes to',\n },\n token: {\n title: 'Authentication Token',\n type: 'string',\n description: 'The token to use for authorization to GitLab',\n },\n commitAction: {\n title: 'Commit action',\n type: 'string',\n enum: ['create', 'update', 'delete'],\n description:\n 'The action to be used for git commit. Defaults to create.',\n },\n removeSourceBranch: {\n title: 'Delete source branch',\n type: 'boolean',\n description:\n 'Option to delete source branch once the MR has been merged. Default: false',\n },\n assignee: {\n title: 'Merge Request Assignee',\n type: 'string',\n description: 'User this merge request will be assigned to',\n },\n },\n },\n output: {\n type: 'object',\n properties: {\n projectid: {\n title: 'Gitlab Project id/Name(slug)',\n type: 'string',\n },\n projectPath: {\n title: 'Gitlab Project path',\n type: 'string',\n },\n mergeRequestUrl: {\n title: 'MergeRequest(MR) URL',\n type: 'string',\n description: 'Link to the merge request in GitLab',\n },\n },\n },\n },\n async handler(ctx) {\n const {\n assignee,\n branchName,\n description,\n repoUrl,\n removeSourceBranch,\n targetPath,\n sourcePath,\n title,\n token: providedToken,\n } = ctx.input;\n\n const { host, owner, repo, project } = parseRepoUrl(\n repoUrl,\n integrations,\n );\n const repoID = project ? project : `${owner}/${repo}`;\n\n const integrationConfig = integrations.gitlab.byHost(host);\n\n if (!integrationConfig) {\n throw new InputError(\n `No matching integration configuration for host ${host}, please check your integrations config`,\n );\n }\n\n if (!integrationConfig.config.token && !providedToken) {\n throw new InputError(`No token available for host ${host}`);\n }\n\n const token = providedToken ?? integrationConfig.config.token!;\n const tokenType = providedToken ? 'oauthToken' : 'token';\n\n const api = new Gitlab({\n host: integrationConfig.config.baseUrl,\n [tokenType]: token,\n });\n\n let assigneeId = undefined;\n\n if (assignee !== undefined) {\n try {\n const assigneeUser = await api.Users.username(assignee);\n assigneeId = assigneeUser[0].id;\n } catch (e) {\n ctx.logger.warn(\n `Failed to find gitlab user id for ${assignee}: ${e}. Proceeding with MR creation without an assignee.`,\n );\n }\n }\n\n let fileRoot: string;\n if (sourcePath) {\n fileRoot = resolveSafeChildPath(ctx.workspacePath, sourcePath);\n } else if (targetPath) {\n // for backward compatibility\n fileRoot = resolveSafeChildPath(ctx.workspacePath, targetPath);\n } else {\n fileRoot = ctx.workspacePath;\n }\n\n const fileContents = await serializeDirectoryContents(fileRoot, {\n gitignore: true,\n });\n\n const actions: Types.CommitAction[] = fileContents.map(file => ({\n action: ctx.input.commitAction ?? 'create',\n filePath: targetPath\n ? path.posix.join(targetPath, file.path)\n : file.path,\n encoding: 'base64',\n content: file.content.toString('base64'),\n execute_filemode: file.executable,\n }));\n\n const projects = await api.Projects.show(repoID);\n\n const { default_branch: defaultBranch } = projects;\n\n try {\n await api.Branches.create(repoID, branchName, String(defaultBranch));\n } catch (e) {\n throw new InputError(\n `The branch creation failed. Please check that your repo does not already contain a branch named '${branchName}'. ${e}`,\n );\n }\n\n try {\n await api.Commits.create(repoID, branchName, ctx.input.title, actions);\n } catch (e) {\n throw new InputError(\n `Committing the changes to ${branchName} failed. Please check that none of the files created by the template already exists. ${e}`,\n );\n }\n\n try {\n const mergeRequestUrl = await api.MergeRequests.create(\n repoID,\n branchName,\n String(defaultBranch),\n title,\n {\n description,\n removeSourceBranch: removeSourceBranch ? removeSourceBranch : false,\n assigneeId,\n },\n ).then((mergeRequest: { web_url: string }) => {\n return mergeRequest.web_url;\n });\n ctx.output('projectid', repoID);\n ctx.output('projectPath', repoID);\n ctx.output('mergeRequestUrl', mergeRequestUrl);\n } catch (e) {\n throw new InputError(`Merge request creation failed${e}`);\n }\n },\n });\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UrlReader } from '@backstage/backend-common';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubCredentialsProvider,\n ScmIntegrations,\n} from '@backstage/integration';\nimport { TemplateAction } from '@backstage/plugin-scaffolder-node';\nimport {\n createCatalogRegisterAction,\n createCatalogWriteAction,\n createFetchCatalogEntityAction,\n} from './catalog';\n\nimport { TemplateFilter, TemplateGlobal } from '../../../lib';\nimport { createDebugLogAction, createWaitAction } from './debug';\nimport {\n createFetchPlainAction,\n createFetchPlainFileAction,\n createFetchTemplateAction,\n} from './fetch';\nimport {\n createFilesystemDeleteAction,\n createFilesystemRenameAction,\n} from './filesystem';\nimport {\n createGithubActionsDispatchAction,\n createGithubIssuesLabelAction,\n createGithubRepoCreateAction,\n createGithubRepoPushAction,\n createGithubWebhookAction,\n} from './github';\nimport {\n createPublishAzureAction,\n createPublishBitbucketAction,\n createPublishBitbucketCloudAction,\n createPublishBitbucketServerAction,\n createPublishGerritAction,\n createPublishGerritReviewAction,\n createPublishGithubAction,\n createPublishGithubPullRequestAction,\n createPublishGitlabAction,\n createPublishGitlabMergeRequestAction,\n} from './publish';\n\n/**\n * The options passed to {@link createBuiltinActions}\n * @public\n */\nexport interface CreateBuiltInActionsOptions {\n /**\n * The {@link @backstage/backend-common#UrlReader} interface that will be used in the default actions.\n */\n reader: UrlReader;\n /**\n * The {@link @backstage/integrations#ScmIntegrations} that will be used in the default actions.\n */\n integrations: ScmIntegrations;\n /**\n * The {@link @backstage/catalog-client#CatalogApi} that will be used in the default actions.\n */\n catalogClient: CatalogApi;\n /**\n * The {@link @backstage/config#Config} that will be used in the default actions.\n */\n config: Config;\n /**\n * Additional custom filters that will be passed to the nunjucks template engine for use in\n * Template Manifests and also template skeleton files when using `fetch:template`.\n */\n additionalTemplateFilters?: Record<string, TemplateFilter>;\n additionalTemplateGlobals?: Record<string, TemplateGlobal>;\n}\n\n/**\n * A function to generate create a list of default actions that the scaffolder provides.\n * Is called internally in the default setup, but can be used when adding your own actions or overriding the default ones\n *\n * @public\n * @returns A list of actions that can be used in the scaffolder\n */\nexport const createBuiltinActions = (\n options: CreateBuiltInActionsOptions,\n): TemplateAction[] => {\n const {\n reader,\n integrations,\n catalogClient,\n config,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n } = options;\n\n const githubCredentialsProvider: GithubCredentialsProvider =\n DefaultGithubCredentialsProvider.fromIntegrations(integrations);\n\n const actions = [\n createFetchPlainAction({\n reader,\n integrations,\n }),\n createFetchPlainFileAction({\n reader,\n integrations,\n }),\n createFetchTemplateAction({\n integrations,\n reader,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n }),\n createPublishGerritAction({\n integrations,\n config,\n }),\n createPublishGerritReviewAction({\n integrations,\n config,\n }),\n createPublishGithubAction({\n integrations,\n config,\n githubCredentialsProvider,\n }),\n createPublishGithubPullRequestAction({\n integrations,\n githubCredentialsProvider,\n }),\n createPublishGitlabAction({\n integrations,\n config,\n }),\n createPublishGitlabMergeRequestAction({\n integrations,\n }),\n createPublishBitbucketAction({\n integrations,\n config,\n }),\n createPublishBitbucketCloudAction({\n integrations,\n config,\n }),\n createPublishBitbucketServerAction({\n integrations,\n config,\n }),\n createPublishAzureAction({\n integrations,\n config,\n }),\n createDebugLogAction(),\n createWaitAction(),\n createCatalogRegisterAction({ catalogClient, integrations }),\n createFetchCatalogEntityAction({ catalogClient }),\n createCatalogWriteAction(),\n createFilesystemDeleteAction(),\n createFilesystemRenameAction(),\n createGithubActionsDispatchAction({\n integrations,\n githubCredentialsProvider,\n }),\n createGithubWebhookAction({\n integrations,\n githubCredentialsProvider,\n }),\n createGithubIssuesLabelAction({\n integrations,\n githubCredentialsProvider,\n }),\n createGithubRepoCreateAction({\n integrations,\n githubCredentialsProvider,\n }),\n createGithubRepoPushAction({\n integrations,\n config,\n githubCredentialsProvider,\n }),\n ];\n\n return actions as TemplateAction[];\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConflictError, NotFoundError } from '@backstage/errors';\nimport { TemplateAction } from '@backstage/plugin-scaffolder-node';\n/**\n * Registry of all registered template actions.\n * @public\n */\nexport class TemplateActionRegistry {\n private readonly actions = new Map<string, TemplateAction>();\n\n register(action: TemplateAction) {\n if (this.actions.has(action.id)) {\n throw new ConflictError(\n `Template action with ID '${action.id}' has already been registered`,\n );\n }\n\n this.actions.set(action.id, action);\n }\n\n get(actionId: string): TemplateAction {\n const action = this.actions.get(actionId);\n if (!action) {\n throw new NotFoundError(\n `Template action with ID '${actionId}' is not registered.`,\n );\n }\n return action;\n }\n\n list(): TemplateAction[] {\n return [...this.actions.values()];\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '@backstage/types';\nimport {\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { ConflictError, NotFoundError } from '@backstage/errors';\nimport { Knex } from 'knex';\nimport { v4 as uuid } from 'uuid';\nimport {\n SerializedTaskEvent,\n SerializedTask,\n TaskStatus,\n TaskEventType,\n TaskStore,\n TaskStoreEmitOptions,\n TaskStoreListEventsOptions,\n TaskStoreCreateTaskOptions,\n TaskStoreCreateTaskResult,\n TaskStoreShutDownTaskOptions,\n} from './types';\nimport { DateTime } from 'luxon';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-scaffolder-backend',\n 'migrations',\n);\n\nexport type RawDbTaskRow = {\n id: string;\n spec: string;\n status: TaskStatus;\n last_heartbeat_at?: string;\n created_at: string;\n created_by: string | null;\n secrets?: string | null;\n};\n\nexport type RawDbTaskEventRow = {\n id: number;\n task_id: string;\n body: string;\n event_type: TaskEventType;\n created_at: string;\n};\n\n/**\n * DatabaseTaskStore\n *\n * @public\n */\nexport type DatabaseTaskStoreOptions = {\n database: PluginDatabaseManager | Knex;\n};\n\n/**\n * Typeguard to help DatabaseTaskStore understand when database is PluginDatabaseManager vs. when database is a Knex instance.\n *\n * * @public\n */\nfunction isPluginDatabaseManager(\n opt: PluginDatabaseManager | Knex,\n): opt is PluginDatabaseManager {\n return (opt as PluginDatabaseManager).getClient !== undefined;\n}\n\nconst parseSqlDateToIsoString = <T>(input: T): T | string => {\n if (typeof input === 'string') {\n return DateTime.fromSQL(input, { zone: 'UTC' }).toISO();\n }\n\n return input;\n};\n\n/**\n * DatabaseTaskStore\n *\n * @public\n */\nexport class DatabaseTaskStore implements TaskStore {\n private readonly db: Knex;\n\n static async create(\n options: DatabaseTaskStoreOptions,\n ): Promise<DatabaseTaskStore> {\n const { database } = options;\n const client = await this.getClient(database);\n\n await this.runMigrations(database, client);\n\n return new DatabaseTaskStore(client);\n }\n\n private static async getClient(\n database: PluginDatabaseManager | Knex,\n ): Promise<Knex> {\n if (isPluginDatabaseManager(database)) {\n return database.getClient();\n }\n\n return database;\n }\n\n private static async runMigrations(\n database: PluginDatabaseManager | Knex,\n client: Knex,\n ): Promise<void> {\n if (!isPluginDatabaseManager(database)) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n\n return;\n }\n\n if (!database.migrations?.skip) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n }\n\n private constructor(client: Knex) {\n this.db = client;\n }\n\n async list(options: {\n createdBy?: string;\n }): Promise<{ tasks: SerializedTask[] }> {\n const queryBuilder = this.db<RawDbTaskRow>('tasks');\n\n if (options.createdBy) {\n queryBuilder.where({\n created_by: options.createdBy,\n });\n }\n\n const results = await queryBuilder.orderBy('created_at', 'desc').select();\n\n const tasks = results.map(result => ({\n id: result.id,\n spec: JSON.parse(result.spec),\n status: result.status,\n createdBy: result.created_by ?? undefined,\n lastHeartbeatAt: parseSqlDateToIsoString(result.last_heartbeat_at),\n createdAt: parseSqlDateToIsoString(result.created_at),\n }));\n\n return { tasks };\n }\n\n async getTask(taskId: string): Promise<SerializedTask> {\n const [result] = await this.db<RawDbTaskRow>('tasks')\n .where({ id: taskId })\n .select();\n if (!result) {\n throw new NotFoundError(`No task with id '${taskId}' found`);\n }\n try {\n const spec = JSON.parse(result.spec);\n const secrets = result.secrets ? JSON.parse(result.secrets) : undefined;\n return {\n id: result.id,\n spec,\n status: result.status,\n lastHeartbeatAt: parseSqlDateToIsoString(result.last_heartbeat_at),\n createdAt: parseSqlDateToIsoString(result.created_at),\n createdBy: result.created_by ?? undefined,\n secrets,\n };\n } catch (error) {\n throw new Error(`Failed to parse spec of task '${taskId}', ${error}`);\n }\n }\n\n async createTask(\n options: TaskStoreCreateTaskOptions,\n ): Promise<TaskStoreCreateTaskResult> {\n const taskId = uuid();\n await this.db<RawDbTaskRow>('tasks').insert({\n id: taskId,\n spec: JSON.stringify(options.spec),\n secrets: options.secrets ? JSON.stringify(options.secrets) : undefined,\n created_by: options.createdBy ?? null,\n status: 'open',\n });\n return { taskId };\n }\n\n async claimTask(): Promise<SerializedTask | undefined> {\n return this.db.transaction(async tx => {\n const [task] = await tx<RawDbTaskRow>('tasks')\n .where({\n status: 'open',\n })\n .limit(1)\n .select();\n\n if (!task) {\n return undefined;\n }\n\n const updateCount = await tx<RawDbTaskRow>('tasks')\n .where({ id: task.id, status: 'open' })\n .update({\n status: 'processing',\n last_heartbeat_at: this.db.fn.now(),\n // remove the secrets when moving to processing state.\n secrets: null,\n });\n\n if (updateCount < 1) {\n return undefined;\n }\n\n try {\n const spec = JSON.parse(task.spec);\n const secrets = task.secrets ? JSON.parse(task.secrets) : undefined;\n return {\n id: task.id,\n spec,\n status: 'processing',\n lastHeartbeatAt: task.last_heartbeat_at,\n createdAt: task.created_at,\n createdBy: task.created_by ?? undefined,\n secrets,\n };\n } catch (error) {\n throw new Error(`Failed to parse spec of task '${task.id}', ${error}`);\n }\n });\n }\n\n async heartbeatTask(taskId: string): Promise<void> {\n const updateCount = await this.db<RawDbTaskRow>('tasks')\n .where({ id: taskId, status: 'processing' })\n .update({\n last_heartbeat_at: this.db.fn.now(),\n });\n if (updateCount === 0) {\n throw new ConflictError(`No running task with taskId ${taskId} found`);\n }\n }\n\n async listStaleTasks(options: { timeoutS: number }): Promise<{\n tasks: { taskId: string }[];\n }> {\n const { timeoutS } = options;\n\n const rawRows = await this.db<RawDbTaskRow>('tasks')\n .where('status', 'processing')\n .andWhere(\n 'last_heartbeat_at',\n '<=',\n this.db.client.config.client.includes('sqlite3')\n ? this.db.raw(`datetime('now', ?)`, [`-${timeoutS} seconds`])\n : this.db.raw(`? - interval '${timeoutS} seconds'`, [\n this.db.fn.now(),\n ]),\n );\n const tasks = rawRows.map(row => ({\n taskId: row.id,\n }));\n return { tasks };\n }\n\n async completeTask(options: {\n taskId: string;\n status: TaskStatus;\n eventBody: JsonObject;\n }): Promise<void> {\n const { taskId, status, eventBody } = options;\n\n let oldStatus: string;\n if (['failed', 'completed', 'cancelled'].includes(status)) {\n oldStatus = 'processing';\n } else {\n throw new Error(\n `Invalid status update of run '${taskId}' to status '${status}'`,\n );\n }\n\n await this.db.transaction(async tx => {\n const [task] = await tx<RawDbTaskRow>('tasks')\n .where({\n id: taskId,\n })\n .limit(1)\n .select();\n\n const updateTask = async (criteria: {\n id: string;\n status?: TaskStatus;\n }) => {\n const updateCount = await tx<RawDbTaskRow>('tasks')\n .where(criteria)\n .update({\n status,\n });\n\n if (updateCount !== 1) {\n throw new ConflictError(\n `Failed to update status to '${status}' for taskId ${taskId}`,\n );\n }\n\n await tx<RawDbTaskEventRow>('task_events').insert({\n task_id: taskId,\n event_type: 'completion',\n body: JSON.stringify(eventBody),\n });\n };\n\n if (status === 'cancelled') {\n await updateTask({\n id: taskId,\n });\n return;\n }\n\n if (task.status === 'cancelled') {\n return;\n }\n\n if (!task) {\n throw new Error(`No task with taskId ${taskId} found`);\n }\n if (task.status !== oldStatus) {\n throw new ConflictError(\n `Refusing to update status of run '${taskId}' to status '${status}' ` +\n `as it is currently '${task.status}', expected '${oldStatus}'`,\n );\n }\n\n await updateTask({\n id: taskId,\n status: oldStatus,\n });\n });\n }\n\n async emitLogEvent(\n options: TaskStoreEmitOptions<{ message: string } & JsonObject>,\n ): Promise<void> {\n const { taskId, body } = options;\n const serializedBody = JSON.stringify(body);\n await this.db<RawDbTaskEventRow>('task_events').insert({\n task_id: taskId,\n event_type: 'log',\n body: serializedBody,\n });\n }\n\n async listEvents(\n options: TaskStoreListEventsOptions,\n ): Promise<{ events: SerializedTaskEvent[] }> {\n const { taskId, after } = options;\n const rawEvents = await this.db<RawDbTaskEventRow>('task_events')\n .where({\n task_id: taskId,\n })\n .andWhere(builder => {\n if (typeof after === 'number') {\n builder.where('id', '>', after).orWhere('event_type', 'completion');\n }\n })\n .orderBy('id')\n .select();\n\n const events = rawEvents.map(event => {\n try {\n const body = JSON.parse(event.body) as JsonObject;\n return {\n id: Number(event.id),\n taskId,\n body,\n type: event.event_type,\n createdAt: parseSqlDateToIsoString(event.created_at),\n };\n } catch (error) {\n throw new Error(\n `Failed to parse event body from event taskId=${taskId} id=${event.id}, ${error}`,\n );\n }\n });\n return { events };\n }\n\n async shutdownTask(options: TaskStoreShutDownTaskOptions): Promise<void> {\n const { taskId } = options;\n const message = `This task was marked as stale as it exceeded its timeout`;\n\n const statusStepEvents = (await this.listEvents({ taskId })).events.filter(\n ({ body }) => body?.stepId,\n );\n\n const completedSteps = statusStepEvents\n .filter(\n ({ body: { status } }) => status === 'failed' || status === 'completed',\n )\n .map(step => step.body.stepId);\n\n const hungProcessingSteps = statusStepEvents\n .filter(({ body: { status } }) => status === 'processing')\n .map(event => event.body.stepId)\n .filter(step => !completedSteps.includes(step));\n\n for (const step of hungProcessingSteps) {\n await this.emitLogEvent({\n taskId,\n body: {\n message,\n stepId: step,\n status: 'failed',\n },\n });\n }\n\n await this.completeTask({\n taskId,\n status: 'failed',\n eventBody: {\n message,\n },\n });\n }\n\n async cancelTask(\n options: TaskStoreEmitOptions<{ message: string } & JsonObject>,\n ): Promise<void> {\n const { taskId, body } = options;\n const serializedBody = JSON.stringify(body);\n await this.db<RawDbTaskEventRow>('task_events').insert({\n task_id: taskId,\n event_type: 'cancelled',\n body: serializedBody,\n });\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TaskSpec } from '@backstage/plugin-scaffolder-common';\nimport { TaskSecrets } from '@backstage/plugin-scaffolder-node';\nimport { JsonObject, Observable } from '@backstage/types';\nimport { Logger } from 'winston';\nimport ObservableImpl from 'zen-observable';\nimport {\n SerializedTask,\n SerializedTaskEvent,\n TaskBroker,\n TaskBrokerDispatchOptions,\n TaskCompletionState,\n TaskContext,\n TaskStore,\n} from './types';\n\n/**\n * TaskManager\n *\n * @public\n */\nexport class TaskManager implements TaskContext {\n private isDone = false;\n\n private heartbeatTimeoutId?: ReturnType<typeof setInterval>;\n\n static create(\n task: CurrentClaimedTask,\n storage: TaskStore,\n abortSignal: AbortSignal,\n logger: Logger,\n ) {\n const agent = new TaskManager(task, storage, abortSignal, logger);\n agent.startTimeout();\n return agent;\n }\n\n // Runs heartbeat internally\n private constructor(\n private readonly task: CurrentClaimedTask,\n private readonly storage: TaskStore,\n private readonly signal: AbortSignal,\n private readonly logger: Logger,\n ) {}\n\n get spec() {\n return this.task.spec;\n }\n\n get cancelSignal() {\n return this.signal;\n }\n\n get secrets() {\n return this.task.secrets;\n }\n\n get createdBy() {\n return this.task.createdBy;\n }\n\n async getWorkspaceName() {\n return this.task.taskId;\n }\n\n get done() {\n return this.isDone;\n }\n\n async emitLog(message: string, logMetadata?: JsonObject): Promise<void> {\n await this.storage.emitLogEvent({\n taskId: this.task.taskId,\n body: { message, ...logMetadata },\n });\n }\n\n async complete(\n result: TaskCompletionState,\n metadata?: JsonObject,\n ): Promise<void> {\n await this.storage.completeTask({\n taskId: this.task.taskId,\n status: result === 'failed' ? 'failed' : 'completed',\n eventBody: {\n message: `Run completed with status: ${result}`,\n ...metadata,\n },\n });\n this.isDone = true;\n if (this.heartbeatTimeoutId) {\n clearTimeout(this.heartbeatTimeoutId);\n }\n }\n\n private startTimeout() {\n this.heartbeatTimeoutId = setTimeout(async () => {\n try {\n await this.storage.heartbeatTask(this.task.taskId);\n this.startTimeout();\n } catch (error) {\n this.isDone = true;\n\n this.logger.error(\n `Heartbeat for task ${this.task.taskId} failed`,\n error,\n );\n }\n }, 1000);\n }\n}\n\n/**\n * Stores the state of the current claimed task passed to the TaskContext\n *\n * @public\n */\nexport interface CurrentClaimedTask {\n /**\n * The TaskSpec of the current claimed task.\n */\n spec: TaskSpec;\n /**\n * The uuid of the current claimed task.\n */\n taskId: string;\n /**\n * The secrets that are stored with the task.\n */\n secrets?: TaskSecrets;\n /**\n * The creator of the task.\n */\n createdBy?: string;\n}\n\nfunction defer() {\n let resolve = () => {};\n const promise = new Promise<void>(_resolve => {\n resolve = _resolve;\n });\n return { promise, resolve };\n}\n\nexport class StorageTaskBroker implements TaskBroker {\n constructor(\n private readonly storage: TaskStore,\n private readonly logger: Logger,\n ) {}\n\n async list(options?: {\n createdBy?: string;\n }): Promise<{ tasks: SerializedTask[] }> {\n if (!this.storage.list) {\n throw new Error(\n 'TaskStore does not implement the list method. Please implement the list method to be able to list tasks',\n );\n }\n return await this.storage.list({ createdBy: options?.createdBy });\n }\n\n private deferredDispatch = defer();\n\n private async registerCancellable(\n taskId: string,\n abortController: AbortController,\n ) {\n let shouldUnsubscribe = false;\n const subscription = this.event$({ taskId, after: undefined }).subscribe({\n error: _ => {\n subscription.unsubscribe();\n },\n next: ({ events }) => {\n for (const event of events) {\n if (event.type === 'cancelled') {\n abortController.abort();\n shouldUnsubscribe = true;\n }\n\n if (event.type === 'completion') {\n shouldUnsubscribe = true;\n }\n }\n if (shouldUnsubscribe) {\n subscription.unsubscribe();\n }\n },\n });\n }\n\n /**\n * {@inheritdoc TaskBroker.claim}\n */\n async claim(): Promise<TaskContext> {\n for (;;) {\n const pendingTask = await this.storage.claimTask();\n if (pendingTask) {\n const abortController = new AbortController();\n await this.registerCancellable(pendingTask.id, abortController);\n return TaskManager.create(\n {\n taskId: pendingTask.id,\n spec: pendingTask.spec,\n secrets: pendingTask.secrets,\n createdBy: pendingTask.createdBy,\n },\n this.storage,\n abortController.signal,\n this.logger,\n );\n }\n\n await this.waitForDispatch();\n }\n }\n\n /**\n * {@inheritdoc TaskBroker.dispatch}\n */\n async dispatch(\n options: TaskBrokerDispatchOptions,\n ): Promise<{ taskId: string }> {\n const taskRow = await this.storage.createTask(options);\n this.signalDispatch();\n return {\n taskId: taskRow.taskId,\n };\n }\n\n /**\n * {@inheritdoc TaskBroker.get}\n */\n async get(taskId: string): Promise<SerializedTask> {\n return this.storage.getTask(taskId);\n }\n\n /**\n * {@inheritdoc TaskBroker.event$}\n */\n event$(options: {\n taskId: string;\n after?: number;\n }): Observable<{ events: SerializedTaskEvent[] }> {\n return new ObservableImpl(observer => {\n const { taskId } = options;\n\n let after = options.after;\n let cancelled = false;\n\n (async () => {\n while (!cancelled) {\n const result = await this.storage.listEvents({ taskId, after });\n const { events } = result;\n if (events.length) {\n after = events[events.length - 1].id;\n observer.next(result);\n }\n\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n })();\n\n return () => {\n cancelled = true;\n };\n });\n }\n\n /**\n * {@inheritdoc TaskBroker.vacuumTasks}\n */\n async vacuumTasks(options: { timeoutS: number }): Promise<void> {\n const { tasks } = await this.storage.listStaleTasks(options);\n await Promise.all(\n tasks.map(async task => {\n try {\n await this.storage.completeTask({\n taskId: task.taskId,\n status: 'failed',\n eventBody: {\n message:\n 'The task was cancelled because the task worker lost connection to the task broker',\n },\n });\n } catch (error) {\n this.logger.warn(`Failed to cancel task '${task.taskId}', ${error}`);\n }\n }),\n );\n }\n\n private waitForDispatch() {\n return this.deferredDispatch.promise;\n }\n\n private signalDispatch() {\n this.deferredDispatch.resolve();\n this.deferredDispatch = defer();\n }\n\n async cancel(taskId: string) {\n const { events } = await this.storage.listEvents({ taskId });\n const currentStepId =\n events.length > 0\n ? events\n .filter(({ body }) => body?.stepId)\n .reduce((prev, curr) => (prev.id > curr.id ? prev : curr)).body\n .stepId\n : 0;\n\n await this.storage.cancelTask?.({\n taskId,\n body: {\n message: `Step ${currentStepId} has been cancelled.`,\n stepId: currentStepId,\n status: 'cancelled',\n },\n });\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isArray } from 'lodash';\nimport { Schema } from 'jsonschema';\n\n/**\n * Returns true if the input is not `false`, `undefined`, `null`, `\"\"`, `0`, or\n * `[]`. This behavior is based on the behavior of handlebars, see\n * https://handlebarsjs.com/guide/builtin-helpers.html#if\n */\nexport function isTruthy(value: any): boolean {\n return isArray(value) ? value.length > 0 : !!value;\n}\n\nexport function generateExampleOutput(schema: Schema): unknown {\n const { examples } = schema as { examples?: unknown };\n if (examples && Array.isArray(examples)) {\n return examples[0];\n }\n if (schema.type === 'object') {\n return Object.fromEntries(\n Object.entries(schema.properties ?? {}).map(([key, value]) => [\n key,\n generateExampleOutput(value),\n ]),\n );\n } else if (schema.type === 'array') {\n const [firstSchema] = [schema.items]?.flat();\n if (firstSchema) {\n return [generateExampleOutput(firstSchema)];\n }\n return [];\n } else if (schema.type === 'string') {\n return '<example>';\n } else if (schema.type === 'number') {\n return 0;\n } else if (schema.type === 'boolean') {\n return false;\n }\n return '<unknown>';\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Counter,\n CounterConfiguration,\n Gauge,\n GaugeConfiguration,\n Histogram,\n HistogramConfiguration,\n register,\n Summary,\n SummaryConfiguration,\n} from 'prom-client';\n\nexport function createCounterMetric<T extends string>(\n config: CounterConfiguration<T>,\n): Counter<T> {\n let metric = register.getSingleMetric(config.name);\n if (!metric) {\n metric = new Counter<T>(config);\n register.registerMetric(metric);\n }\n return metric as Counter<T>;\n}\n\nexport function createGaugeMetric<T extends string>(\n config: GaugeConfiguration<T>,\n): Gauge<T> {\n let metric = register.getSingleMetric(config.name);\n if (!metric) {\n metric = new Gauge<T>(config);\n register.registerMetric(metric);\n }\n return metric as Gauge<T>;\n}\n\nexport function createSummaryMetric<T extends string>(\n config: SummaryConfiguration<T>,\n): Summary<T> {\n let metric = register.getSingleMetric(config.name);\n if (!metric) {\n metric = new Summary<T>(config);\n register.registerMetric(metric);\n }\n\n return metric as Summary<T>;\n}\n\nexport function createHistogramMetric<T extends string>(\n config: HistogramConfiguration<T>,\n): Histogram<T> {\n let metric = register.getSingleMetric(config.name);\n if (!metric) {\n metric = new Histogram<T>(config);\n register.registerMetric(metric);\n }\n\n return metric as Histogram<T>;\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { makeCreatePermissionRule } from '@backstage/plugin-permission-node';\nimport {\n RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n RESOURCE_TYPE_SCAFFOLDER_ACTION,\n} from '@backstage/plugin-scaffolder-common/alpha';\n\nimport {\n TemplateEntityStepV1beta3,\n TemplateParametersV1beta3,\n} from '@backstage/plugin-scaffolder-common';\n\nimport { z } from 'zod';\nimport { JsonObject, JsonPrimitive } from '@backstage/types';\nimport { get } from 'lodash';\n\nexport const createTemplatePermissionRule = makeCreatePermissionRule<\n TemplateEntityStepV1beta3 | TemplateParametersV1beta3,\n {},\n typeof RESOURCE_TYPE_SCAFFOLDER_TEMPLATE\n>();\n\nexport const hasTag = createTemplatePermissionRule({\n name: 'HAS_TAG',\n resourceType: RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n description: `Match parameters or steps with the given tag`,\n paramsSchema: z.object({\n tag: z.string().describe('Name of the tag to match on'),\n }),\n apply: (resource, { tag }) => {\n return resource['backstage:permissions']?.tags?.includes(tag) ?? false;\n },\n toQuery: () => ({}),\n});\n\nexport const createActionPermissionRule = makeCreatePermissionRule<\n {\n action: string;\n input: JsonObject | undefined;\n },\n {},\n typeof RESOURCE_TYPE_SCAFFOLDER_ACTION\n>();\n\nexport const hasActionId = createActionPermissionRule({\n name: 'HAS_ACTION_ID',\n resourceType: RESOURCE_TYPE_SCAFFOLDER_ACTION,\n description: `Match actions with the given actionId`,\n paramsSchema: z.object({\n actionId: z.string().describe('Name of the actionId to match on'),\n }),\n apply: (resource, { actionId }) => {\n return resource.action === actionId;\n },\n toQuery: () => ({}),\n});\n\nexport const hasProperty = buildHasProperty({\n name: 'HAS_PROPERTY',\n valueSchema: z.union([z.string(), z.number(), z.boolean(), z.null()]),\n validateProperty: false,\n});\n\nexport const hasBooleanProperty = buildHasProperty({\n name: 'HAS_BOOLEAN_PROPERTY',\n valueSchema: z.boolean(),\n});\nexport const hasNumberProperty = buildHasProperty({\n name: 'HAS_NUMBER_PROPERTY',\n valueSchema: z.number(),\n});\nexport const hasStringProperty = buildHasProperty({\n name: 'HAS_STRING_PROPERTY',\n valueSchema: z.string(),\n});\n\nfunction buildHasProperty<Schema extends z.ZodType<JsonPrimitive>>({\n name,\n valueSchema,\n validateProperty = true,\n}: {\n name: string;\n valueSchema: Schema;\n validateProperty?: boolean;\n}) {\n return createActionPermissionRule({\n name,\n description: `Allow actions with the specified property`,\n resourceType: RESOURCE_TYPE_SCAFFOLDER_ACTION,\n paramsSchema: z.object({\n key: z\n .string()\n .describe(`Property within the action parameters to match on`),\n value: valueSchema.describe(`Value of the given property to match on`),\n }) as unknown as z.ZodType<{ key: string; value?: z.infer<Schema> }>,\n apply: (resource, { key, value }) => {\n const foundValue = get(resource.input, key);\n\n if (validateProperty && !valueSchema.safeParse(foundValue).success) {\n return false;\n }\n if (value !== undefined) {\n if (valueSchema.safeParse(value).success) {\n return value === foundValue;\n }\n return false;\n }\n\n return foundValue !== undefined;\n },\n toQuery: () => ({}),\n });\n}\n\nexport const scaffolderTemplateRules = { hasTag };\nexport const scaffolderActionRules = {\n hasActionId,\n hasBooleanProperty,\n hasNumberProperty,\n hasStringProperty,\n};\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ScmIntegrations } from '@backstage/integration';\nimport {\n TaskContext,\n TaskTrackType,\n WorkflowResponse,\n WorkflowRunner,\n} from './types';\nimport * as winston from 'winston';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport nunjucks from 'nunjucks';\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport { InputError, NotAllowedError } from '@backstage/errors';\nimport { PassThrough } from 'stream';\nimport { generateExampleOutput, isTruthy } from './helper';\nimport { validate as validateJsonSchema } from 'jsonschema';\nimport { TemplateActionRegistry } from '../actions';\nimport {\n TemplateFilter,\n SecureTemplater,\n SecureTemplateRenderer,\n TemplateGlobal,\n} from '../../lib/templating/SecureTemplater';\nimport {\n TaskSpec,\n TaskSpecV1beta3,\n TaskStep,\n} from '@backstage/plugin-scaffolder-common';\n\nimport { TemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { createConditionAuthorizer } from '@backstage/plugin-permission-node';\nimport { UserEntity } from '@backstage/catalog-model';\nimport { createCounterMetric, createHistogramMetric } from '../../util/metrics';\nimport { createDefaultFilters } from '../../lib/templating/filters';\nimport {\n AuthorizeResult,\n PermissionEvaluator,\n PolicyDecision,\n} from '@backstage/plugin-permission-common';\nimport { scaffolderActionRules } from '../../service/rules';\nimport { actionExecutePermission } from '@backstage/plugin-scaffolder-common/alpha';\n\ntype NunjucksWorkflowRunnerOptions = {\n workingDirectory: string;\n actionRegistry: TemplateActionRegistry;\n integrations: ScmIntegrations;\n logger: winston.Logger;\n additionalTemplateFilters?: Record<string, TemplateFilter>;\n additionalTemplateGlobals?: Record<string, TemplateGlobal>;\n permissions?: PermissionEvaluator;\n};\n\ntype TemplateContext = {\n parameters: JsonObject;\n steps: {\n [stepName: string]: { output: { [outputName: string]: JsonValue } };\n };\n secrets?: Record<string, string>;\n user?: {\n entity?: UserEntity;\n ref?: string;\n };\n};\n\nconst isValidTaskSpec = (taskSpec: TaskSpec): taskSpec is TaskSpecV1beta3 => {\n return taskSpec.apiVersion === 'scaffolder.backstage.io/v1beta3';\n};\n\nconst createStepLogger = ({\n task,\n step,\n}: {\n task: TaskContext;\n step: TaskStep;\n}) => {\n const metadata = { stepId: step.id };\n const taskLogger = winston.createLogger({\n level: process.env.LOG_LEVEL || 'info',\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.simple(),\n ),\n defaultMeta: {},\n });\n\n const streamLogger = new PassThrough();\n streamLogger.on('data', async data => {\n const message = data.toString().trim();\n if (message?.length > 1) {\n await task.emitLog(message, metadata);\n }\n });\n\n taskLogger.add(new winston.transports.Stream({ stream: streamLogger }));\n\n return { taskLogger, streamLogger };\n};\n\nconst isActionAuthorized = createConditionAuthorizer(\n Object.values(scaffolderActionRules),\n);\n\nexport class NunjucksWorkflowRunner implements WorkflowRunner {\n private readonly defaultTemplateFilters: Record<string, TemplateFilter>;\n constructor(private readonly options: NunjucksWorkflowRunnerOptions) {\n this.defaultTemplateFilters = createDefaultFilters({\n integrations: this.options.integrations,\n });\n }\n\n private readonly tracker = scaffoldingTracker();\n\n private isSingleTemplateString(input: string) {\n const { parser, nodes } = nunjucks as unknown as {\n parser: {\n parse(\n template: string,\n ctx: object,\n options: nunjucks.ConfigureOptions,\n ): { children: { children?: unknown[] }[] };\n };\n nodes: { TemplateData: Function };\n };\n\n const parsed = parser.parse(\n input,\n {},\n {\n autoescape: false,\n tags: {\n variableStart: '${{',\n variableEnd: '}}',\n },\n },\n );\n\n return (\n parsed.children.length === 1 &&\n !(parsed.children[0]?.children?.[0] instanceof nodes.TemplateData)\n );\n }\n\n private render<T>(\n input: T,\n context: TemplateContext,\n renderTemplate: SecureTemplateRenderer,\n ): T {\n return JSON.parse(JSON.stringify(input), (_key, value) => {\n try {\n if (typeof value === 'string') {\n try {\n if (this.isSingleTemplateString(value)) {\n // Lets convert ${{ parameters.bob }} to ${{ (parameters.bob) | dump }} so we can keep the input type\n const wrappedDumped = value.replace(\n /\\${{(.+)}}/g,\n '${{ ( $1 ) | dump }}',\n );\n\n // Run the templating\n const templated = renderTemplate(wrappedDumped, context);\n\n // If there's an empty string returned, then it's undefined\n if (templated === '') {\n return undefined;\n }\n\n // Reparse the dumped string\n return JSON.parse(templated);\n }\n } catch (ex) {\n this.options.logger.error(\n `Failed to parse template string: ${value} with error ${ex.message}`,\n );\n }\n\n // Fallback to default behaviour\n const templated = renderTemplate(value, context);\n\n if (templated === '') {\n return undefined;\n }\n\n return templated;\n }\n } catch {\n return value;\n }\n return value;\n });\n }\n\n async executeStep(\n task: TaskContext,\n step: TaskStep,\n context: TemplateContext,\n renderTemplate: (template: string, values: unknown) => string,\n taskTrack: TaskTrackType,\n workspacePath: string,\n decision: PolicyDecision,\n ) {\n const stepTrack = await this.tracker.stepStart(task, step);\n\n if (task.cancelSignal.aborted) {\n throw new Error(`Step ${step.name} has been cancelled.`);\n }\n\n try {\n if (step.if) {\n const ifResult = await this.render(step.if, context, renderTemplate);\n if (!isTruthy(ifResult)) {\n await stepTrack.skipFalsy();\n return;\n }\n }\n\n const action: TemplateAction<JsonObject> =\n this.options.actionRegistry.get(step.action);\n const { taskLogger, streamLogger } = createStepLogger({ task, step });\n\n if (task.isDryRun) {\n const redactedSecrets = Object.fromEntries(\n Object.entries(task.secrets ?? {}).map(secret => [\n secret[0],\n '[REDACTED]',\n ]),\n );\n const debugInput =\n (step.input &&\n this.render(\n step.input,\n {\n ...context,\n secrets: redactedSecrets,\n },\n renderTemplate,\n )) ??\n {};\n taskLogger.info(\n `Running ${\n action.id\n } in dry-run mode with inputs (secrets redacted): ${JSON.stringify(\n debugInput,\n undefined,\n 2,\n )}`,\n );\n if (!action.supportsDryRun) {\n await taskTrack.skipDryRun(step, action);\n const outputSchema = action.schema?.output;\n if (outputSchema) {\n context.steps[step.id] = {\n output: generateExampleOutput(outputSchema) as {\n [name in string]: JsonValue;\n },\n };\n } else {\n context.steps[step.id] = { output: {} };\n }\n return;\n }\n }\n\n // Secrets are only passed when templating the input to actions for security reasons\n const input =\n (step.input &&\n this.render(\n step.input,\n { ...context, secrets: task.secrets ?? {} },\n renderTemplate,\n )) ??\n {};\n\n if (action.schema?.input) {\n const validateResult = validateJsonSchema(input, action.schema.input);\n if (!validateResult.valid) {\n const errors = validateResult.errors.join(', ');\n throw new InputError(\n `Invalid input passed to action ${action.id}, ${errors}`,\n );\n }\n }\n\n if (!isActionAuthorized(decision, { action: action.id, input })) {\n throw new NotAllowedError(\n `Unauthorized action: ${\n action.id\n }. The action is not allowed. Input: ${JSON.stringify(\n input,\n null,\n 2,\n )}`,\n );\n }\n\n const tmpDirs = new Array<string>();\n const stepOutput: { [outputName: string]: JsonValue } = {};\n\n await action.handler({\n input,\n secrets: task.secrets ?? {},\n logger: taskLogger,\n logStream: streamLogger,\n workspacePath,\n createTemporaryDirectory: async () => {\n const tmpDir = await fs.mkdtemp(`${workspacePath}_step-${step.id}-`);\n tmpDirs.push(tmpDir);\n return tmpDir;\n },\n output(name: string, value: JsonValue) {\n stepOutput[name] = value;\n },\n templateInfo: task.spec.templateInfo,\n user: task.spec.user,\n isDryRun: task.isDryRun,\n signal: task.cancelSignal,\n });\n\n // Remove all temporary directories that were created when executing the action\n for (const tmpDir of tmpDirs) {\n await fs.remove(tmpDir);\n }\n\n context.steps[step.id] = { output: stepOutput };\n\n if (task.cancelSignal.aborted) {\n throw new Error(`Step ${step.name} has been cancelled.`);\n }\n\n await stepTrack.markSuccessful();\n } catch (err) {\n await taskTrack.markFailed(step, err);\n await stepTrack.markFailed();\n throw err;\n }\n }\n\n async execute(task: TaskContext): Promise<WorkflowResponse> {\n if (!isValidTaskSpec(task.spec)) {\n throw new InputError(\n 'Wrong template version executed with the workflow engine',\n );\n }\n const workspacePath = path.join(\n this.options.workingDirectory,\n await task.getWorkspaceName(),\n );\n\n const { additionalTemplateFilters, additionalTemplateGlobals } =\n this.options;\n\n const renderTemplate = await SecureTemplater.loadRenderer({\n templateFilters: {\n ...this.defaultTemplateFilters,\n ...additionalTemplateFilters,\n },\n templateGlobals: additionalTemplateGlobals,\n });\n\n try {\n const taskTrack = await this.tracker.taskStart(task);\n await fs.ensureDir(workspacePath);\n\n const context: TemplateContext = {\n parameters: task.spec.parameters,\n steps: {},\n user: task.spec.user,\n };\n\n const [decision]: PolicyDecision[] =\n this.options.permissions && task.spec.steps.length\n ? await this.options.permissions.authorizeConditional(\n [{ permission: actionExecutePermission }],\n { token: task.secrets?.backstageToken },\n )\n : [{ result: AuthorizeResult.ALLOW }];\n\n for (const step of task.spec.steps) {\n await this.executeStep(\n task,\n step,\n context,\n renderTemplate,\n taskTrack,\n workspacePath,\n decision,\n );\n }\n\n const output = this.render(task.spec.output, context, renderTemplate);\n await taskTrack.markSuccessful();\n\n return { output };\n } finally {\n if (workspacePath) {\n await fs.remove(workspacePath);\n }\n }\n }\n}\n\nfunction scaffoldingTracker() {\n const taskCount = createCounterMetric({\n name: 'scaffolder_task_count',\n help: 'Count of task runs',\n labelNames: ['template', 'user', 'result'],\n });\n const taskDuration = createHistogramMetric({\n name: 'scaffolder_task_duration',\n help: 'Duration of a task run',\n labelNames: ['template', 'result'],\n });\n const stepCount = createCounterMetric({\n name: 'scaffolder_step_count',\n help: 'Count of step runs',\n labelNames: ['template', 'step', 'result'],\n });\n const stepDuration = createHistogramMetric({\n name: 'scaffolder_step_duration',\n help: 'Duration of a step runs',\n labelNames: ['template', 'step', 'result'],\n });\n\n async function taskStart(task: TaskContext) {\n await task.emitLog(`Starting up task with ${task.spec.steps.length} steps`);\n const template = task.spec.templateInfo?.entityRef || '';\n const user = task.spec.user?.ref || '';\n\n const taskTimer = taskDuration.startTimer({\n template,\n });\n\n async function skipDryRun(\n step: TaskStep,\n action: TemplateAction<JsonObject>,\n ) {\n task.emitLog(`Skipping because ${action.id} does not support dry-run`, {\n stepId: step.id,\n status: 'skipped',\n });\n }\n\n async function markSuccessful() {\n taskCount.inc({\n template,\n user,\n result: 'ok',\n });\n taskTimer({ result: 'ok' });\n }\n\n async function markFailed(step: TaskStep, err: Error) {\n await task.emitLog(String(err.stack), {\n stepId: step.id,\n status: 'failed',\n });\n taskCount.inc({\n template,\n user,\n result: 'failed',\n });\n taskTimer({ result: 'failed' });\n }\n\n async function markCancelled(step: TaskStep) {\n await task.emitLog(`Step ${step.id} has been cancelled.`, {\n stepId: step.id,\n status: 'cancelled',\n });\n taskCount.inc({\n template,\n user,\n result: 'cancelled',\n });\n taskTimer({ result: 'cancelled' });\n }\n\n return {\n skipDryRun,\n markCancelled,\n markSuccessful,\n markFailed,\n };\n }\n\n async function stepStart(task: TaskContext, step: TaskStep) {\n await task.emitLog(`Beginning step ${step.name}`, {\n stepId: step.id,\n status: 'processing',\n });\n const template = task.spec.templateInfo?.entityRef || '';\n\n const stepTimer = stepDuration.startTimer({\n template,\n step: step.name,\n });\n\n async function markSuccessful() {\n await task.emitLog(`Finished step ${step.name}`, {\n stepId: step.id,\n status: 'completed',\n });\n stepCount.inc({\n template,\n step: step.name,\n result: 'ok',\n });\n stepTimer({ result: 'ok' });\n }\n\n async function markCancelled() {\n stepCount.inc({\n template,\n step: step.name,\n result: 'cancelled',\n });\n stepTimer({ result: 'cancelled' });\n }\n\n async function markFailed() {\n stepCount.inc({\n template,\n step: step.name,\n result: 'failed',\n });\n stepTimer({ result: 'failed' });\n }\n\n async function skipFalsy() {\n await task.emitLog(\n `Skipping step ${step.id} because its if condition was false`,\n { stepId: step.id, status: 'skipped' },\n );\n stepTimer({ result: 'skipped' });\n }\n\n return {\n markCancelled,\n markFailed,\n markSuccessful,\n skipFalsy,\n };\n }\n\n return {\n taskStart,\n stepStart,\n };\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TaskContext, TaskBroker, WorkflowRunner } from './types';\nimport PQueue from 'p-queue';\nimport { NunjucksWorkflowRunner } from './NunjucksWorkflowRunner';\nimport { Logger } from 'winston';\nimport { TemplateActionRegistry } from '../actions';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { assertError } from '@backstage/errors';\nimport { TemplateFilter, TemplateGlobal } from '../../lib';\nimport { PermissionEvaluator } from '@backstage/plugin-permission-common';\n/**\n * TaskWorkerOptions\n *\n * @public\n */\nexport type TaskWorkerOptions = {\n taskBroker: TaskBroker;\n runners: {\n workflowRunner: WorkflowRunner;\n };\n concurrentTasksLimit: number;\n permissions?: PermissionEvaluator;\n};\n\n/**\n * CreateWorkerOptions\n *\n * @public\n */\nexport type CreateWorkerOptions = {\n taskBroker: TaskBroker;\n actionRegistry: TemplateActionRegistry;\n integrations: ScmIntegrations;\n workingDirectory: string;\n logger: Logger;\n additionalTemplateFilters?: Record<string, TemplateFilter>;\n /**\n * The number of tasks that can be executed at the same time by the worker\n * @defaultValue 10\n * @example\n * ```\n * {\n * concurrentTasksLimit: 1,\n * // OR\n * concurrentTasksLimit: Infinity\n * }\n * ```\n */\n concurrentTasksLimit?: number;\n additionalTemplateGlobals?: Record<string, TemplateGlobal>;\n permissions?: PermissionEvaluator;\n};\n\n/**\n * TaskWorker\n *\n * @public\n */\nexport class TaskWorker {\n private taskQueue: PQueue;\n\n private constructor(private readonly options: TaskWorkerOptions) {\n this.taskQueue = new PQueue({\n concurrency: options.concurrentTasksLimit,\n });\n }\n\n static async create(options: CreateWorkerOptions): Promise<TaskWorker> {\n const {\n taskBroker,\n logger,\n actionRegistry,\n integrations,\n workingDirectory,\n additionalTemplateFilters,\n concurrentTasksLimit = 10, // from 1 to Infinity\n additionalTemplateGlobals,\n permissions,\n } = options;\n\n const workflowRunner = new NunjucksWorkflowRunner({\n actionRegistry,\n integrations,\n logger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n permissions,\n });\n\n return new TaskWorker({\n taskBroker: taskBroker,\n runners: { workflowRunner },\n concurrentTasksLimit,\n permissions,\n });\n }\n\n start() {\n (async () => {\n for (;;) {\n await this.onReadyToClaimTask();\n const task = await this.options.taskBroker.claim();\n this.taskQueue.add(() => this.runOneTask(task));\n }\n })();\n }\n\n protected onReadyToClaimTask(): Promise<void> {\n if (this.taskQueue.pending < this.options.concurrentTasksLimit) {\n return Promise.resolve();\n }\n return new Promise(resolve => {\n // \"next\" event emits when a task completes\n // https://github.com/sindresorhus/p-queue#next\n this.taskQueue.once('next', () => {\n resolve();\n });\n });\n }\n\n async runOneTask(task: TaskContext) {\n try {\n if (task.spec.apiVersion !== 'scaffolder.backstage.io/v1beta3') {\n throw new Error(\n `Unsupported Template apiVersion ${task.spec.apiVersion}`,\n );\n }\n\n const { output } = await this.options.runners.workflowRunner.execute(\n task,\n );\n\n await task.complete('completed', { output });\n } catch (error) {\n assertError(error);\n await task.complete('failed', {\n error: { name: error.name, message: error.message },\n });\n }\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TemplateAction } from '@backstage/plugin-scaffolder-node';\nimport { TemplateActionRegistry } from '../actions';\n\n/** @internal */\nexport class DecoratedActionsRegistry extends TemplateActionRegistry {\n constructor(\n private readonly innerRegistry: TemplateActionRegistry,\n extraActions: Array<TemplateAction>,\n ) {\n super();\n for (const action of extraActions) {\n this.register(action);\n }\n }\n\n get(actionId: string): TemplateAction {\n try {\n return super.get(actionId);\n } catch {\n return this.innerRegistry.get(actionId);\n }\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ScmIntegrations } from '@backstage/integration';\nimport { TaskSpec } from '@backstage/plugin-scaffolder-common';\nimport { JsonObject } from '@backstage/types';\nimport { v4 as uuid } from 'uuid';\nimport { pathToFileURL } from 'url';\nimport { Logger } from 'winston';\nimport {\n deserializeDirectoryContents,\n SerializedFile,\n serializeDirectoryContents,\n} from '../../lib/files';\nimport { TemplateFilter, TemplateGlobal } from '../../lib';\nimport { TemplateActionRegistry } from '../actions';\nimport { NunjucksWorkflowRunner } from '../tasks/NunjucksWorkflowRunner';\nimport { DecoratedActionsRegistry } from './DecoratedActionsRegistry';\nimport fs from 'fs-extra';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\nimport {\n createTemplateAction,\n TaskSecrets,\n} from '@backstage/plugin-scaffolder-node';\nimport { PermissionEvaluator } from '@backstage/plugin-permission-common';\n\ninterface DryRunInput {\n spec: TaskSpec;\n secrets?: TaskSecrets;\n directoryContents: SerializedFile[];\n}\n\ninterface DryRunResult {\n log: Array<{ body: JsonObject }>;\n directoryContents: SerializedFile[];\n output: JsonObject;\n}\n\n/** @internal */\nexport type TemplateTesterCreateOptions = {\n logger: Logger;\n integrations: ScmIntegrations;\n actionRegistry: TemplateActionRegistry;\n workingDirectory: string;\n additionalTemplateFilters?: Record<string, TemplateFilter>;\n additionalTemplateGlobals?: Record<string, TemplateGlobal>;\n permissions?: PermissionEvaluator;\n};\n\n/**\n * Executes a dry-run of the provided template.\n *\n * The provided content will be extracted into a temporary directory\n * which is then use as the base for any relative file fetch paths.\n *\n * @internal\n */\nexport function createDryRunner(options: TemplateTesterCreateOptions) {\n return async function dryRun(input: DryRunInput): Promise<DryRunResult> {\n let contentPromise;\n\n const workflowRunner = new NunjucksWorkflowRunner({\n ...options,\n actionRegistry: new DecoratedActionsRegistry(options.actionRegistry, [\n createTemplateAction({\n id: 'dry-run:extract',\n supportsDryRun: true,\n async handler(ctx) {\n contentPromise = serializeDirectoryContents(ctx.workspacePath);\n await contentPromise.catch(() => {});\n },\n }),\n ]),\n });\n\n const dryRunId = uuid();\n const log = new Array<{ body: JsonObject }>();\n const contentsPath = resolveSafeChildPath(\n options.workingDirectory,\n `dry-run-content-${dryRunId}`,\n );\n\n try {\n await deserializeDirectoryContents(contentsPath, input.directoryContents);\n\n const abortSignal = new AbortController().signal;\n\n const result = await workflowRunner.execute({\n spec: {\n ...input.spec,\n steps: [\n ...input.spec.steps,\n {\n id: dryRunId,\n name: 'dry-run:extract',\n action: 'dry-run:extract',\n },\n ],\n templateInfo: {\n entityRef: 'template:default/dry-run',\n baseUrl: pathToFileURL(\n resolveSafeChildPath(contentsPath, 'template.yaml'),\n ).toString(),\n },\n },\n secrets: input.secrets,\n // No need to update this at the end of the run, so just hard-code it\n done: false,\n isDryRun: true,\n getWorkspaceName: async () => `dry-run-${dryRunId}`,\n cancelSignal: abortSignal,\n async emitLog(message: string, logMetadata?: JsonObject) {\n if (logMetadata?.stepId === dryRunId) {\n return;\n }\n log.push({\n body: {\n ...logMetadata,\n message,\n },\n });\n },\n complete: async () => {\n throw new Error('Not implemented');\n },\n });\n\n if (!contentPromise) {\n throw new Error('Content extraction step was skipped');\n }\n const directoryContents = await contentPromise;\n\n return {\n log,\n directoryContents,\n output: result.output,\n };\n } finally {\n await fs.remove(contentsPath);\n }\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n Entity,\n ANNOTATION_LOCATION,\n parseLocationRef,\n ANNOTATION_SOURCE_LOCATION,\n CompoundEntityRef,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { assertError, InputError, NotFoundError } from '@backstage/errors';\nimport { TemplateEntityV1beta3 } from '@backstage/plugin-scaffolder-common';\nimport fs from 'fs-extra';\nimport os from 'os';\nimport { Logger } from 'winston';\n\nexport async function getWorkingDirectory(\n config: Config,\n logger: Logger,\n): Promise<string> {\n if (!config.has('backend.workingDirectory')) {\n return os.tmpdir();\n }\n\n const workingDirectory = config.getString('backend.workingDirectory');\n try {\n // Check if working directory exists and is writable\n await fs.access(workingDirectory, fs.constants.F_OK | fs.constants.W_OK);\n logger.info(`using working directory: ${workingDirectory}`);\n } catch (err) {\n assertError(err);\n logger.error(\n `working directory ${workingDirectory} ${\n err.code === 'ENOENT' ? 'does not exist' : 'is not writable'\n }`,\n );\n throw err;\n }\n return workingDirectory;\n}\n\n/**\n * Gets the base URL of the entity location that points to the source location\n * of the entity description within a repo. If there is not source location\n * or if it has an invalid type, undefined will be returned instead.\n *\n * For file locations this will return a `file://` URL.\n */\nexport function getEntityBaseUrl(entity: Entity): string | undefined {\n let location = entity.metadata.annotations?.[ANNOTATION_SOURCE_LOCATION];\n if (!location) {\n location = entity.metadata.annotations?.[ANNOTATION_LOCATION];\n }\n if (!location) {\n return undefined;\n }\n\n const { type, target } = parseLocationRef(location);\n if (type === 'url') {\n return target;\n } else if (type === 'file') {\n return `file://${target}`;\n }\n\n // Only url and file location are handled, as we otherwise don't know if\n // what the url is pointing to makes sense to use as a baseUrl\n return undefined;\n}\n\n/**\n * Will use the provided CatalogApi to go find the given template entity with an additional token.\n * Returns the matching template, or throws a NotFoundError if no such template existed.\n */\nexport async function findTemplate(options: {\n entityRef: CompoundEntityRef;\n token?: string;\n catalogApi: CatalogApi;\n}): Promise<TemplateEntityV1beta3> {\n const { entityRef, token, catalogApi } = options;\n\n if (entityRef.kind.toLocaleLowerCase('en-US') !== 'template') {\n throw new InputError(`Invalid kind, only 'Template' kind is supported`);\n }\n\n const template = await catalogApi.getEntityByRef(entityRef, { token });\n if (!template) {\n throw new NotFoundError(\n `Template ${stringifyEntityRef(entityRef)} not found`,\n );\n }\n\n return template as TemplateEntityV1beta3;\n}\n\nexport type TemplateTransform = (\n template: TemplateEntityV1beta3,\n) => TemplateEntityV1beta3;\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PluginDatabaseManager, UrlReader } from '@backstage/backend-common';\nimport { PluginTaskScheduler } from '@backstage/backend-tasks';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n CompoundEntityRef,\n Entity,\n parseEntityRef,\n stringifyEntityRef,\n UserEntity,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { InputError, NotFoundError, stringifyError } from '@backstage/errors';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport {\n TaskSpec,\n TemplateEntityV1beta3,\n templateEntityV1beta3Validator,\n TemplateParametersV1beta3,\n TemplateEntityStepV1beta3,\n} from '@backstage/plugin-scaffolder-common';\nimport {\n RESOURCE_TYPE_SCAFFOLDER_ACTION,\n RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n scaffolderActionPermissions,\n scaffolderTemplatePermissions,\n templateParameterReadPermission,\n templateStepReadPermission,\n} from '@backstage/plugin-scaffolder-common/alpha';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { validate } from 'jsonschema';\nimport { Logger } from 'winston';\nimport { z } from 'zod';\nimport { TemplateFilter, TemplateGlobal } from '../lib';\nimport {\n createBuiltinActions,\n DatabaseTaskStore,\n TaskBroker,\n TaskWorker,\n TemplateActionRegistry,\n} from '../scaffolder';\nimport { createDryRunner } from '../scaffolder/dryrun';\nimport { StorageTaskBroker } from '../scaffolder/tasks/StorageTaskBroker';\nimport { findTemplate, getEntityBaseUrl, getWorkingDirectory } from './helpers';\nimport {\n IdentityApi,\n IdentityApiGetIdentityRequest,\n} from '@backstage/plugin-auth-node';\nimport { TemplateAction } from '@backstage/plugin-scaffolder-node';\nimport {\n PermissionEvaluator,\n PermissionRuleParams,\n} from '@backstage/plugin-permission-common';\nimport {\n createConditionAuthorizer,\n createPermissionIntegrationRouter,\n PermissionRule,\n} from '@backstage/plugin-permission-node';\nimport { scaffolderActionRules, scaffolderTemplateRules } from './rules';\n\n/**\n *\n * @public\n */\nexport type TemplatePermissionRuleInput<\n TParams extends PermissionRuleParams = PermissionRuleParams,\n> = PermissionRule<\n TemplateEntityStepV1beta3 | TemplateParametersV1beta3,\n {},\n typeof RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n TParams\n>;\nfunction isTemplatePermissionRuleInput(\n permissionRule: TemplatePermissionRuleInput | ActionPermissionRuleInput,\n): permissionRule is TemplatePermissionRuleInput {\n return permissionRule.resourceType === RESOURCE_TYPE_SCAFFOLDER_TEMPLATE;\n}\n\n/**\n *\n * @public\n */\nexport type ActionPermissionRuleInput<\n TParams extends PermissionRuleParams = PermissionRuleParams,\n> = PermissionRule<\n TemplateEntityStepV1beta3 | TemplateParametersV1beta3,\n {},\n typeof RESOURCE_TYPE_SCAFFOLDER_ACTION,\n TParams\n>;\nfunction isActionPermissionRuleInput(\n permissionRule: TemplatePermissionRuleInput | ActionPermissionRuleInput,\n): permissionRule is ActionPermissionRuleInput {\n return permissionRule.resourceType === RESOURCE_TYPE_SCAFFOLDER_ACTION;\n}\n\n/**\n * RouterOptions\n *\n * @public\n */\nexport interface RouterOptions {\n logger: Logger;\n config: Config;\n reader: UrlReader;\n database: PluginDatabaseManager;\n catalogClient: CatalogApi;\n scheduler?: PluginTaskScheduler;\n actions?: TemplateAction<any, any>[];\n /**\n * @deprecated taskWorkers is deprecated in favor of concurrentTasksLimit option with a single TaskWorker\n * @defaultValue 1\n */\n taskWorkers?: number;\n /**\n * Sets the number of concurrent tasks that can be run at any given time on the TaskWorker\n * @defaultValue 10\n */\n concurrentTasksLimit?: number;\n taskBroker?: TaskBroker;\n additionalTemplateFilters?: Record<string, TemplateFilter>;\n additionalTemplateGlobals?: Record<string, TemplateGlobal>;\n permissions?: PermissionEvaluator;\n permissionRules?: Array<\n TemplatePermissionRuleInput | ActionPermissionRuleInput\n >;\n identity?: IdentityApi;\n}\n\nfunction isSupportedTemplate(entity: TemplateEntityV1beta3) {\n return entity.apiVersion === 'scaffolder.backstage.io/v1beta3';\n}\n\n/*\n * @deprecated This function remains as the DefaultIdentityClient behaves slightly differently to the pre-existing\n * scaffolder behaviour. Specifically if the token fails to parse, the DefaultIdentityClient will raise an error.\n * The scaffolder did not raise an error in this case. As such we chose to allow it to behave as it did previously\n * until someone explicitly passes an IdentityApi. When we have reasonable confidence that most backstage deployments\n * are using the IdentityApi, we can remove this function.\n */\nfunction buildDefaultIdentityClient(options: RouterOptions): IdentityApi {\n return {\n getIdentity: async ({ request }: IdentityApiGetIdentityRequest) => {\n const header = request.headers.authorization;\n const { logger } = options;\n\n if (!header) {\n return undefined;\n }\n\n try {\n const token = header.match(/^Bearer\\s(\\S+\\.\\S+\\.\\S+)$/i)?.[1];\n if (!token) {\n throw new TypeError('Expected Bearer with JWT');\n }\n\n const [_header, rawPayload, _signature] = token.split('.');\n const payload: JsonValue = JSON.parse(\n Buffer.from(rawPayload, 'base64').toString(),\n );\n\n if (\n typeof payload !== 'object' ||\n payload === null ||\n Array.isArray(payload)\n ) {\n throw new TypeError('Malformed JWT payload');\n }\n\n const sub = payload.sub;\n if (typeof sub !== 'string') {\n throw new TypeError('Expected string sub claim');\n }\n\n if (sub === 'backstage-server') {\n return undefined;\n }\n\n // Check that it's a valid ref, otherwise this will throw.\n parseEntityRef(sub);\n\n return {\n identity: {\n userEntityRef: sub,\n ownershipEntityRefs: [],\n type: 'user',\n },\n token,\n };\n } catch (e) {\n logger.error(`Invalid authorization header: ${stringifyError(e)}`);\n return undefined;\n }\n },\n };\n}\n\n/**\n * A method to create a router for the scaffolder backend plugin.\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const router = Router();\n // Be generous in upload size to support a wide range of templates in dry-run mode.\n router.use(express.json({ limit: '10MB' }));\n\n const {\n logger: parentLogger,\n config,\n reader,\n database,\n catalogClient,\n actions,\n taskWorkers,\n concurrentTasksLimit,\n scheduler,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n permissions,\n permissionRules,\n } = options;\n\n const logger = parentLogger.child({ plugin: 'scaffolder' });\n\n const identity: IdentityApi =\n options.identity || buildDefaultIdentityClient(options);\n const workingDirectory = await getWorkingDirectory(config, logger);\n const integrations = ScmIntegrations.fromConfig(config);\n\n let taskBroker: TaskBroker;\n if (!options.taskBroker) {\n const databaseTaskStore = await DatabaseTaskStore.create({ database });\n taskBroker = new StorageTaskBroker(databaseTaskStore, logger);\n\n if (scheduler && databaseTaskStore.listStaleTasks) {\n await scheduler.scheduleTask({\n id: 'close_stale_tasks',\n frequency: { cron: '*/5 * * * *' }, // every 5 minutes, also supports Duration\n timeout: { minutes: 15 },\n fn: async () => {\n const { tasks } = await databaseTaskStore.listStaleTasks({\n timeoutS: 86400,\n });\n\n for (const task of tasks) {\n await databaseTaskStore.shutdownTask(task);\n logger.info(`Successfully closed stale task ${task.taskId}`);\n }\n },\n });\n }\n } else {\n taskBroker = options.taskBroker;\n }\n\n const actionRegistry = new TemplateActionRegistry();\n\n const workers = [];\n for (let i = 0; i < (taskWorkers || 1); i++) {\n const worker = await TaskWorker.create({\n taskBroker,\n actionRegistry,\n integrations,\n logger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n concurrentTasksLimit,\n permissions,\n });\n workers.push(worker);\n }\n\n const actionsToRegister = Array.isArray(actions)\n ? actions\n : createBuiltinActions({\n integrations,\n catalogClient,\n reader,\n config,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n });\n\n actionsToRegister.forEach(action => actionRegistry.register(action));\n workers.forEach(worker => worker.start());\n\n const dryRunner = createDryRunner({\n actionRegistry,\n integrations,\n logger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n permissions,\n });\n\n const templateRules: TemplatePermissionRuleInput[] = Object.values(\n scaffolderTemplateRules,\n );\n const actionRules: ActionPermissionRuleInput[] = Object.values(\n scaffolderActionRules,\n );\n\n if (permissionRules) {\n templateRules.push(\n ...permissionRules.filter(isTemplatePermissionRuleInput),\n );\n actionRules.push(...permissionRules.filter(isActionPermissionRuleInput));\n }\n\n const isAuthorized = createConditionAuthorizer(Object.values(templateRules));\n\n const permissionIntegrationRouter = createPermissionIntegrationRouter({\n resources: [\n {\n resourceType: RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n permissions: scaffolderTemplatePermissions,\n rules: templateRules,\n },\n {\n resourceType: RESOURCE_TYPE_SCAFFOLDER_ACTION,\n permissions: scaffolderActionPermissions,\n rules: actionRules,\n },\n ],\n });\n\n router.use(permissionIntegrationRouter);\n\n router\n .get(\n '/v2/templates/:namespace/:kind/:name/parameter-schema',\n async (req, res) => {\n const userIdentity = await identity.getIdentity({\n request: req,\n });\n const token = userIdentity?.token;\n\n const template = await authorizeTemplate(req.params, token);\n\n const parameters = [template.spec.parameters ?? []].flat();\n res.json({\n title: template.metadata.title ?? template.metadata.name,\n description: template.metadata.description,\n 'ui:options': template.metadata['ui:options'],\n steps: parameters.map(schema => ({\n title: schema.title ?? 'Please enter the following information',\n description: schema.description,\n schema,\n })),\n });\n },\n )\n .get('/v2/actions', async (_req, res) => {\n const actionsList = actionRegistry.list().map(action => {\n return {\n id: action.id,\n description: action.description,\n examples: action.examples,\n schema: action.schema,\n };\n });\n res.json(actionsList);\n })\n .post('/v2/tasks', async (req, res) => {\n const templateRef: string = req.body.templateRef;\n const { kind, namespace, name } = parseEntityRef(templateRef, {\n defaultKind: 'template',\n });\n\n const callerIdentity = await identity.getIdentity({\n request: req,\n });\n const token = callerIdentity?.token;\n const userEntityRef = callerIdentity?.identity.userEntityRef;\n\n const userEntity = userEntityRef\n ? await catalogClient.getEntityByRef(userEntityRef, { token })\n : undefined;\n\n let auditLog = `Scaffolding task for ${templateRef}`;\n if (userEntityRef) {\n auditLog += ` created by ${userEntityRef}`;\n }\n logger.info(auditLog);\n\n const values = req.body.values;\n\n const template = await authorizeTemplate(\n { kind, namespace, name },\n token,\n );\n\n for (const parameters of [template.spec.parameters ?? []].flat()) {\n const result = validate(values, parameters);\n\n if (!result.valid) {\n res.status(400).json({ errors: result.errors });\n return;\n }\n }\n\n const baseUrl = getEntityBaseUrl(template);\n\n const taskSpec: TaskSpec = {\n apiVersion: template.apiVersion,\n steps: template.spec.steps.map((step, index) => ({\n ...step,\n id: step.id ?? `step-${index + 1}`,\n name: step.name ?? step.action,\n })),\n output: template.spec.output ?? {},\n parameters: values,\n user: {\n entity: userEntity as UserEntity,\n ref: userEntityRef,\n },\n templateInfo: {\n entityRef: stringifyEntityRef({ kind, name, namespace }),\n baseUrl,\n entity: {\n metadata: template.metadata,\n },\n },\n };\n\n const result = await taskBroker.dispatch({\n spec: taskSpec,\n createdBy: userEntityRef,\n secrets: {\n ...req.body.secrets,\n backstageToken: token,\n },\n });\n\n res.status(201).json({ id: result.taskId });\n })\n .get('/v2/tasks', async (req, res) => {\n const [userEntityRef] = [req.query.createdBy].flat();\n\n if (\n typeof userEntityRef !== 'string' &&\n typeof userEntityRef !== 'undefined'\n ) {\n throw new InputError('createdBy query parameter must be a string');\n }\n\n if (!taskBroker.list) {\n throw new Error(\n 'TaskBroker does not support listing tasks, please implement the list method on the TaskBroker.',\n );\n }\n\n const tasks = await taskBroker.list({\n createdBy: userEntityRef,\n });\n\n res.status(200).json(tasks);\n })\n .get('/v2/tasks/:taskId', async (req, res) => {\n const { taskId } = req.params;\n const task = await taskBroker.get(taskId);\n if (!task) {\n throw new NotFoundError(`Task with id ${taskId} does not exist`);\n }\n // Do not disclose secrets\n delete task.secrets;\n res.status(200).json(task);\n })\n .post('/v2/tasks/:taskId/cancel', async (req, res) => {\n const { taskId } = req.params;\n await taskBroker.cancel?.(taskId);\n res.status(200).json({ status: 'cancelled' });\n })\n .get('/v2/tasks/:taskId/eventstream', async (req, res) => {\n const { taskId } = req.params;\n const after =\n req.query.after !== undefined ? Number(req.query.after) : undefined;\n\n logger.debug(`Event stream observing taskId '${taskId}' opened`);\n\n // Mandatory headers and http status to keep connection open\n res.writeHead(200, {\n Connection: 'keep-alive',\n 'Cache-Control': 'no-cache',\n 'Content-Type': 'text/event-stream',\n });\n\n // After client opens connection send all events as string\n const subscription = taskBroker.event$({ taskId, after }).subscribe({\n error: error => {\n logger.error(\n `Received error from event stream when observing taskId '${taskId}', ${error}`,\n );\n res.end();\n },\n next: ({ events }) => {\n let shouldUnsubscribe = false;\n for (const event of events) {\n res.write(\n `event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`,\n );\n if (event.type === 'completion') {\n shouldUnsubscribe = true;\n }\n }\n // res.flush() is only available with the compression middleware\n res.flush?.();\n if (shouldUnsubscribe) {\n subscription.unsubscribe();\n res.end();\n }\n },\n });\n\n // When client closes connection we update the clients list\n // avoiding the disconnected one\n req.on('close', () => {\n subscription.unsubscribe();\n logger.debug(`Event stream observing taskId '${taskId}' closed`);\n });\n })\n .get('/v2/tasks/:taskId/events', async (req, res) => {\n const { taskId } = req.params;\n const after = Number(req.query.after) || undefined;\n\n // cancel the request after 30 seconds. this aligns with the recommendations of RFC 6202.\n const timeout = setTimeout(() => {\n res.json([]);\n }, 30_000);\n\n // Get all known events after an id (always includes the completion event) and return the first callback\n const subscription = taskBroker.event$({ taskId, after }).subscribe({\n error: error => {\n logger.error(\n `Received error from event stream when observing taskId '${taskId}', ${error}`,\n );\n },\n next: ({ events }) => {\n clearTimeout(timeout);\n subscription.unsubscribe();\n res.json(events);\n },\n });\n\n // When client closes connection we update the clients list\n // avoiding the disconnected one\n req.on('close', () => {\n subscription.unsubscribe();\n clearTimeout(timeout);\n });\n })\n .post('/v2/dry-run', async (req, res) => {\n const bodySchema = z.object({\n template: z.unknown(),\n values: z.record(z.unknown()),\n secrets: z.record(z.string()).optional(),\n directoryContents: z.array(\n z.object({ path: z.string(), base64Content: z.string() }),\n ),\n });\n const body = await bodySchema.parseAsync(req.body).catch(e => {\n throw new InputError(`Malformed request: ${e}`);\n });\n\n const template = body.template as TemplateEntityV1beta3;\n if (!(await templateEntityV1beta3Validator.check(template))) {\n throw new InputError('Input template is not a template');\n }\n\n const token = (\n await identity.getIdentity({\n request: req,\n })\n )?.token;\n\n for (const parameters of [template.spec.parameters ?? []].flat()) {\n const result = validate(body.values, parameters);\n if (!result.valid) {\n res.status(400).json({ errors: result.errors });\n return;\n }\n }\n\n const steps = template.spec.steps.map((step, index) => ({\n ...step,\n id: step.id ?? `step-${index + 1}`,\n name: step.name ?? step.action,\n }));\n\n const result = await dryRunner({\n spec: {\n apiVersion: template.apiVersion,\n steps,\n output: template.spec.output ?? {},\n parameters: body.values as JsonObject,\n },\n directoryContents: (body.directoryContents ?? []).map(file => ({\n path: file.path,\n content: Buffer.from(file.base64Content, 'base64'),\n })),\n secrets: {\n ...body.secrets,\n ...(token && { backstageToken: token }),\n },\n });\n\n res.status(200).json({\n ...result,\n steps,\n directoryContents: result.directoryContents.map(file => ({\n path: file.path,\n executable: file.executable,\n base64Content: file.content.toString('base64'),\n })),\n });\n });\n\n const app = express();\n app.set('logger', logger);\n app.use('/', router);\n\n async function authorizeTemplate(\n entityRef: CompoundEntityRef,\n token: string | undefined,\n ) {\n const template = await findTemplate({\n catalogApi: catalogClient,\n entityRef,\n token,\n });\n\n if (!isSupportedTemplate(template)) {\n throw new InputError(\n `Unsupported apiVersion field in schema entity, ${\n (template as Entity).apiVersion\n }`,\n );\n }\n\n if (!permissions) {\n return template;\n }\n\n const [parameterDecision, stepDecision] =\n await permissions.authorizeConditional(\n [\n { permission: templateParameterReadPermission },\n { permission: templateStepReadPermission },\n ],\n { token },\n );\n\n // Authorize parameters\n if (Array.isArray(template.spec.parameters)) {\n template.spec.parameters = template.spec.parameters.filter(step =>\n isAuthorized(parameterDecision, step),\n );\n } else if (\n template.spec.parameters &&\n !isAuthorized(parameterDecision, template.spec.parameters)\n ) {\n template.spec.parameters = undefined;\n }\n\n // Authorize steps\n template.spec.steps = template.spec.steps.filter(step =>\n isAuthorized(stepDecision, step),\n );\n\n return template;\n }\n\n return app;\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Entity,\n getCompoundEntityRef,\n parseEntityRef,\n RELATION_OWNED_BY,\n RELATION_OWNER_OF,\n} from '@backstage/catalog-model';\nimport {\n CatalogProcessor,\n CatalogProcessorEmit,\n processingResult,\n} from '@backstage/plugin-catalog-node';\nimport { LocationSpec } from '@backstage/plugin-catalog-common';\nimport {\n TemplateEntityV1beta3,\n templateEntityV1beta3Validator,\n} from '@backstage/plugin-scaffolder-common';\n\n/** @public */\nexport class ScaffolderEntitiesProcessor implements CatalogProcessor {\n getProcessorName(): string {\n return 'ScaffolderEntitiesProcessor';\n }\n\n private readonly validators = [templateEntityV1beta3Validator];\n\n async validateEntityKind(entity: Entity): Promise<boolean> {\n for (const validator of this.validators) {\n if (await validator.check(entity)) {\n return true;\n }\n }\n\n return false;\n }\n\n async postProcessEntity(\n entity: Entity,\n _location: LocationSpec,\n emit: CatalogProcessorEmit,\n ): Promise<Entity> {\n const selfRef = getCompoundEntityRef(entity);\n\n if (\n entity.apiVersion === 'scaffolder.backstage.io/v1beta3' &&\n entity.kind === 'Template'\n ) {\n const template = entity as TemplateEntityV1beta3;\n\n const target = template.spec.owner;\n if (target) {\n const targetRef = parseEntityRef(target, {\n defaultKind: 'Group',\n defaultNamespace: selfRef.namespace,\n });\n emit(\n processingResult.relation({\n source: selfRef,\n type: RELATION_OWNED_BY,\n target: {\n kind: targetRef.kind,\n namespace: targetRef.namespace,\n name: targetRef.name,\n },\n }),\n );\n emit(\n processingResult.relation({\n source: {\n kind: targetRef.kind,\n namespace: targetRef.namespace,\n name: targetRef.name,\n },\n type: RELATION_OWNER_OF,\n target: selfRef,\n }),\n );\n }\n }\n\n return entity;\n }\n}\n"],"names":["id","examples","yaml","createTemplateAction","InputError","stringifyEntityRef","z","fs","resolveSafeChildPath","parseEntityRef","relative","readdir","join","stat","Duration","_a","path","VM","resolvePackagePath","normalizePath","joinPath","isChildPath","get","globby","extname","isBinaryFile","PassThrough","spawn","Git","assertError","DefaultGithubCredentialsProvider","Sodium","NotFoundError","Octokit","inputProps.repoUrl","inputProps.description","inputProps.homepage","inputProps.access","inputProps.requireCodeOwnerReviews","inputProps.bypassPullRequestAllowances","inputProps.requiredApprovingReviewCount","inputProps.restrictions","inputProps.requiredStatusCheckContexts","inputProps.requireBranchesToBeUpToDate","inputProps.requiredConversationResolution","inputProps.repoVisibility","inputProps.deleteBranchOnMerge","inputProps.allowMergeCommit","inputProps.allowSquashMerge","inputProps.squashMergeCommitTitle","inputProps.squashMergeCommitMessage","inputProps.allowRebaseMerge","inputProps.allowAutoMerge","inputProps.collaborators","inputProps.hasProjects","inputProps.hasWiki","inputProps.hasIssues","inputProps.token","inputProps.topics","inputProps.repoVariables","inputProps.secrets","inputProps.requiredCommitSigning","outputProps.remoteUrl","outputProps.repoContentsUrl","inputProps.dismissStaleReviews","inputProps.defaultBranch","inputProps.protectDefaultBranch","inputProps.protectEnforceAdmins","inputProps.gitCommitMessage","inputProps.gitAuthorName","inputProps.gitAuthorEmail","inputProps.sourcePath","outputProps.commitHash","emitterEventNames","getPersonalAccessTokenHandler","WebApi","fetch","getAuthorizationHeader","performEnableLFS","createRepository","getBitbucketServerRequestOptions","getGerritRequestOptions","crypto","limiterFactory","isError","dirname","CustomErrorBase","createPullRequest","Gitlab","ConflictError","DateTime","uuid","ObservableImpl","isArray","register","Counter","Histogram","makeCreatePermissionRule","RESOURCE_TYPE_SCAFFOLDER_TEMPLATE","RESOURCE_TYPE_SCAFFOLDER_ACTION","winston","createConditionAuthorizer","nunjucks","templated","validateJsonSchema","errors","NotAllowedError","actionExecutePermission","AuthorizeResult","PQueue","pathToFileURL","os","ANNOTATION_SOURCE_LOCATION","ANNOTATION_LOCATION","parseLocationRef","stringifyError","Router","express","ScmIntegrations","createPermissionIntegrationRouter","scaffolderTemplatePermissions","scaffolderActionPermissions","result","validate","_b","templateEntityV1beta3Validator","templateParameterReadPermission","templateStepReadPermission","getCompoundEntityRef","processingResult","RELATION_OWNED_BY","RELATION_OWNER_OF"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAMA,IAAK,GAAA,kBAAA,CAAA;AAEX,MAAMC,UAAW,GAAA;AAAA,EACf;AAAA,IACE,WAAa,EAAA,2BAAA;AAAA,IACb,OAAA,EAASC,yBAAK,SAAU,CAAA;AAAA,MACtB,KAAO,EAAA;AAAA,QACL;AAAA,UACE,MAAQ,EAAAF,IAAA;AAAA,UACR,EAAI,EAAA,uBAAA;AAAA,UACJ,IAAM,EAAA,2BAAA;AAAA,UACN,KAAO,EAAA;AAAA,YACL,cACE,EAAA,qEAAA;AAAA,WACJ;AAAA,SACF;AAAA,OACF;AAAA,KACD,CAAA;AAAA,GACH;AACF,CAAA,CAAA;AAMO,SAAS,4BAA4B,OAGzC,EAAA;AAC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