Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend the shared library to provide more data for bitbucket prs (and use it here) #4141

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21451,7 +21451,7 @@
},
"dependencies": {
"@gitkraken/gitkraken-components": "10.7.0",
"@gitkraken/provider-apis": "0.26.2",
"@gitkraken/provider-apis": "0.26.2+??",
"@gitkraken/shared-web-components": "0.1.1-rc.15",
"@gk-nzaytsev/fast-string-truncated-width": "1.1.0",
"@lit-labs/signals": "0.1.2",
Expand Down
46 changes: 26 additions & 20 deletions src/plus/integrations/providers/bitbucket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { IntegrationAuthenticationProviderDescriptor } from '../authenticat
import type { ProviderAuthenticationSession } from '../authentication/models';
import { HostingIntegration } from '../integration';
import type { BitbucketRepositoryDescriptor, BitbucketWorkspaceDescriptor } from './bitbucket/models';
import { providersMetadata } from './models';
import { fromProviderPullRequest, providersMetadata } from './models';

const metadata = providersMetadata[HostingIntegrationId.Bitbucket];
const authProvider = Object.freeze({ id: metadata.id, scopes: metadata.scopes });
Expand Down Expand Up @@ -207,9 +207,18 @@ export class BitbucketIntegration extends HostingIntegration<
return undefined;
}

const api = await this.getProvidersApi();
if (!api) {
return undefined;
}

const remotes = await flatSettled(this.container.git.openRepositories.map(r => r.git.remotes().getRemotes()));
const workspaceRepos = await nonnullSettled(
remotes.map(async r => ((await r.getIntegration())?.id === this.id ? r.path : undefined)),
remotes.map(async r => {
const integration = await r.getIntegration();
const [namespace, name] = r.path.split('/');
return integration?.id === this.id ? { name: name, namespace: namespace } : undefined;
}),
);

const user = await this.getProviderCurrentAccount(session);
Expand All @@ -218,28 +227,25 @@ export class BitbucketIntegration extends HostingIntegration<
const workspaces = await this.getProviderResourcesForUser(session);
if (workspaces == null || workspaces.length === 0) return undefined;

const api = await this.container.bitbucket;
if (!api) return undefined;

const authoredPrs = workspaces.map(ws =>
api.getPullRequestsForWorkspaceAuthoredByUser(this, session.accessToken, user.id, ws.slug, this.apiBaseUrl),
);
const integration = await this.container.integrations.get(this.id);

const reviewingPrs = workspaceRepos.map(repo => {
const [owner, name] = repo.split('/');
return api.getUsersReviewingPullRequestsForRepo(
this,
session.accessToken,
user.id,
owner,
name,
this.apiBaseUrl,
);
const authoredPrs = workspaces.map(async ws => {
const prs = await api.getBitbucketPullRequestsAuthoredByUserForWorkspace(user.id, ws.slug, {
accessToken: session.accessToken,
});
return prs?.map(pr => fromProviderPullRequest(pr, integration));
});

const reviewingPrs = api
.getPullRequestsForRepos(this.id, workspaceRepos, {
query: `state="OPEN" AND reviewers.uuid="${user.id}"`,
accessToken: session.accessToken,
})
.then(r => r.values?.map(pr => fromProviderPullRequest(pr, integration)));

return [
...uniqueBy(
await flatSettled([...authoredPrs, ...reviewingPrs]),
await flatSettled([...authoredPrs, reviewingPrs]),
pr => pr.url,
(orig, _cur) => orig,
),
Expand Down Expand Up @@ -330,7 +336,7 @@ export function isBitbucketCloudDomain(domain: string | undefined): boolean {
return domain != null && bitbucketCloudDomainRegex.test(domain);
}

type MaybePromiseArr<T> = Promise<T | undefined>[] | (T | undefined)[];
type MaybePromiseArr<T> = (Promise<T | undefined> | T | undefined)[];

async function nonnullSettled<T>(arr: MaybePromiseArr<T>): Promise<T[]> {
const all = await Promise.allSettled(arr);
Expand Down
64 changes: 0 additions & 64 deletions src/plus/integrations/providers/bitbucket/bitbucket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,70 +289,6 @@ export class BitbucketApi implements Disposable {
}
}

async getPullRequestsForWorkspaceAuthoredByUser(
provider: Provider,
token: string,
userUuid: string,
workspace: string,
baseUrl: string,
): Promise<PullRequest[] | undefined> {
const scope = getLogScope();

const response = await this.request<{
values: BitbucketPullRequest[];
pagelen: number;
size: number;
page: number;
}>(
provider,
token,
baseUrl,
`workspaces/${workspace}/pullrequests/${userUuid}?state=OPEN&fields=%2Bvalues.reviewers,%2Bvalues.participants`,
{
method: 'GET',
},
scope,
);

if (!response?.values?.length) {
return undefined;
}
return response.values.map(pr => fromBitbucketPullRequest(pr, provider));
}

async getUsersReviewingPullRequestsForRepo(
provider: Provider,
token: string,
userUuid: string,
owner: string,
repo: string,
baseUrl: string,
): Promise<PullRequest[] | undefined> {
const scope = getLogScope();

const query = encodeURIComponent(`state="OPEN" AND reviewers.uuid="${userUuid}"`);
const response = await this.request<{
values: BitbucketPullRequest[];
pagelen: number;
size: number;
page: number;
}>(
provider,
token,
baseUrl,
`repositories/${owner}/${repo}/pullrequests?q=${query}&state=OPEN&fields=%2Bvalues.reviewers,%2Bvalues.participants`,
{
method: 'GET',
},
scope,
);

if (!response?.values?.length) {
return undefined;
}
return response.values.map(pr => fromBitbucketPullRequest(pr, provider));
}

private async request<T>(
provider: Provider,
token: string,
Expand Down
18 changes: 17 additions & 1 deletion src/plus/integrations/providers/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
Jira,
JiraProject,
JiraResource,
NumberedPageInput,
Issue as ProviderApiIssue,
PullRequestWithUniqueID,
RequestFunction,
Expand Down Expand Up @@ -151,6 +152,7 @@ export interface GetPullRequestsOptions {
assigneeLogins?: string[];
reviewRequestedLogin?: string;
mentionLogin?: string;
query?: string;
cursor?: string; // stringified JSON object of type { type: 'cursor' | 'page'; value: string | number } | {}
baseUrl?: string;
}
Expand Down Expand Up @@ -342,6 +344,19 @@ export type GetBitbucketResourcesForUserFn = (
input: { userId: string },
options?: EnterpriseOptions,
) => Promise<{ data: BitbucketWorkspaceStub[] }>;
export type GetBitbucketPullRequestsAuthoredByUserForWorkspaceFn = (
input: {
userId: string;
workspaceSlug: string;
} & NumberedPageInput,
options?: EnterpriseOptions,
) => Promise<{
pageInfo: {
hasNextPage: boolean;
nextPage: number | null;
};
data: GitPullRequest[];
}>;
export type GetIssuesForProjectFn = Jira['getIssuesForProject'];
export type GetIssuesForResourceForCurrentUserFn = (
input: { resourceId: string },
Expand All @@ -364,6 +379,7 @@ export interface ProviderInfo extends ProviderMetadata {
getJiraResourcesForCurrentUserFn?: GetJiraResourcesForCurrentUserFn;
getAzureResourcesForUserFn?: GetAzureResourcesForUserFn;
getBitbucketResourcesForUserFn?: GetBitbucketResourcesForUserFn;
getBitbucketPullRequestsAuthoredByUserForWorkspaceFn?: GetBitbucketPullRequestsAuthoredByUserForWorkspaceFn;
getJiraProjectsForResourcesFn?: GetJiraProjectsForResourcesFn;
getAzureProjectsForResourceFn?: GetAzureProjectsForResourceFn;
getIssuesForProjectFn?: GetIssuesForProjectFn;
Expand Down Expand Up @@ -912,7 +928,7 @@ export function fromProviderPullRequest(
integration,
fromProviderAccount(pr.author),
pr.id,
pr.graphQLId,
pr.graphQLId || pr.id,
pr.title,
pr.url ?? '',
{
Expand Down
28 changes: 28 additions & 0 deletions src/plus/integrations/providers/providersApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type { IntegrationAuthenticationService } from '../authentication/integra
import type {
GetAzureProjectsForResourceFn,
GetAzureResourcesForUserFn,
GetBitbucketPullRequestsAuthoredByUserForWorkspaceFn,
GetBitbucketResourcesForUserFn,
GetCurrentUserFn,
GetCurrentUserForInstanceFn,
Expand Down Expand Up @@ -202,6 +203,10 @@ export class ProvidersApi {
getBitbucketResourcesForUserFn: providerApis.bitbucket.getWorkspacesForUser.bind(
providerApis.bitbucket,
) as GetBitbucketResourcesForUserFn,
getBitbucketPullRequestsAuthoredByUserForWorkspaceFn:
providerApis.bitbucket.getPullRequestsForUserAndWorkspace.bind(
providerApis.bitbucket,
) as GetBitbucketPullRequestsAuthoredByUserForWorkspaceFn,
getPullRequestsForReposFn: providerApis.bitbucket.getPullRequestsForRepos.bind(
providerApis.bitbucket,
) as GetPullRequestsForReposFn,
Expand Down Expand Up @@ -564,6 +569,29 @@ export class ProvidersApi {
}
}

async getBitbucketPullRequestsAuthoredByUserForWorkspace(
userId: string,
workspaceSlug: string,
options?: { accessToken?: string },
): Promise<ProviderPullRequest[] | undefined> {
const { provider, token } = await this.ensureProviderTokenAndFunction(
HostingIntegrationId.Bitbucket,
'getBitbucketPullRequestsAuthoredByUserForWorkspaceFn',
options?.accessToken,
);

try {
return (
await provider.getBitbucketPullRequestsAuthoredByUserForWorkspaceFn?.(
{ userId: userId, workspaceSlug: workspaceSlug },
{ token: token },
)
)?.data;
} catch (e) {
return this.handleProviderError(HostingIntegrationId.Bitbucket, token, e);
}
}

async getJiraProjectsForResources(
resourceIds: string[],
options?: { accessToken?: string },
Expand Down