Merge pull request #25031 from knowacki23/scaffolder-backend-module-bitbucket-server_-_targetBranch-as-default-repo-branch-instead-of-hardcoded

[Scaffolder Bitbucket Server] Use repository default branch as target branch instead of hardcoded targetBranch
This commit is contained in:
Ben Lambert
2024-06-25 10:53:52 +02:00
committed by GitHub
3 changed files with 69 additions and 2 deletions
+6
View File
@@ -0,0 +1,6 @@
---
'@backstage/plugin-scaffolder-backend-module-bitbucket-server': patch
---
Instead of using hardcoded `targetBranch` now fetch the default branch from Bitbucket repository.
This prevents from errors when no `targetBranch` is provided and the default repository branch is different from `master`, for example: `main`.
@@ -103,6 +103,14 @@ describe('publish:bitbucketServer:pull-request', () => {
],
start: 0,
};
const responseOfDefaultBranch = {
id: 'refs/heads/main',
displayId: 'main',
type: 'BRANCH',
latestCommit: '1245346tsdfgdf',
latestChangeset: 'wsdfgdh234',
isDefault: true,
};
const responseOfPullRequests = {
id: 19,
version: 0,
@@ -190,6 +198,16 @@ describe('publish:bitbucketServer:pull-request', () => {
);
},
),
rest.get(
'https://hosted.bitbucket.com/rest/api/1.0/projects/project/repos/repo/default-branch',
(_, res, ctx) => {
return res(
ctx.status(200),
ctx.set('Content-Type', 'application/json'),
ctx.json(responseOfDefaultBranch),
);
},
),
rest.post(
'https://hosted.bitbucket.com/rest/api/1.0/projects/project/repos/repo/pull-requests',
(_, res, ctx) => {
@@ -204,6 +204,39 @@ const createBranch = async (opts: {
return await response.json();
};
const getDefaultBranch = async (opts: {
project: string;
repo: string;
authorization: string;
apiBaseUrl: string;
}) => {
const { project, repo, authorization, apiBaseUrl } = opts;
let response: Response;
const options: RequestInit = {
method: 'GET',
headers: {
Authorization: authorization,
'Content-Type': 'application/json',
},
};
try {
response = await fetch(
`${apiBaseUrl}/projects/${project}/repos/${repo}/default-branch`,
options,
);
} catch (error) {
throw error;
}
const { displayId } = await response.json();
const defaultBranch = displayId;
if (!defaultBranch) {
throw new Error(`Could not fetch default branch for ${project}/${repo}`);
}
return defaultBranch;
};
/**
* Creates a BitbucketServer Pull Request action.
* @public
@@ -288,7 +321,7 @@ export function createPublishBitbucketServerPullRequestAction(options: {
repoUrl,
title,
description,
targetBranch = 'master',
targetBranch,
sourceBranch,
gitAuthorName,
gitAuthorEmail,
@@ -326,10 +359,20 @@ export function createPublishBitbucketServerPullRequestAction(options: {
const apiBaseUrl = integrationConfig.config.apiBaseUrl;
let finalTargetBranch = targetBranch;
if (!finalTargetBranch) {
finalTargetBranch = await getDefaultBranch({
project,
repo,
authorization,
apiBaseUrl,
});
}
const toRef = await findBranches({
project,
repo,
branchName: targetBranch,
branchName: finalTargetBranch!,
authorization,
apiBaseUrl,
});