Skip to content

Commit

Permalink
fix: gitlab private repo auth
Browse files Browse the repository at this point in the history
  • Loading branch information
conwnet committed Feb 23, 2024
1 parent b07c5d8 commit 2189398
Show file tree
Hide file tree
Showing 34 changed files with 729 additions and 251 deletions.
2 changes: 1 addition & 1 deletion api/vscode-unpkg/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
"got": "^11.8.5"
},
"devDependencies": {
"@vercel/node": "^2.5.7"
"@vercel/node": "^3.0.20"
}
}
692 changes: 592 additions & 100 deletions api/vscode-unpkg/yarn.lock

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions extensions/github1s/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -562,22 +562,22 @@
{
"command": "github1s.commands.openFilePreviousRevision",
"when": "resourceScheme =~ /^(github1s|gitlab1s|bitbucket1s)/",
"group": "navigation@98"
"group": "navigation@4"
},
{
"command": "github1s.commands.openFileNextRevision",
"when": "resourceScheme =~ /^(github1s|gitlab1s|bitbucket1s)/",
"group": "navigation@99"
"group": "navigation@5"
},
{
"command": "github1s.commands.openEditorGutterBlame",
"when": "!isInDiffEditor && github1s:features:gutterBlame:enabled && !github1s:features:gutterBlame:open",
"group": "navigation@4"
"group": "navigation@6"
},
{
"command": "github1s.commands.closeEditorGutterBlame",
"when": "!isInDiffEditor && github1s:features:gutterBlame:enabled && github1s:features:gutterBlame:open",
"group": "navigation@4"
"group": "navigation@6"
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class GitHub1sAuthenticationView {
authenticationFormTitle: 'Authenticating to GitHub',
OAuthButtonText: 'Connect to GitHub',
OAuthButtonLogo: 'assets/pages/assets/github.svg',
createTokenLink: 'https://github.com/settings/tokens/new?scopes=repo&description=GitHub1s',
createTokenLink: `${GITHUB_ORIGIN}/settings/tokens/new?scopes=repo&description=GitHub1s`,
rateLimitDocLink: 'https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting',
rateLimitDocLinkText: 'GitHub Rate limiting Documentation',
authenticationFeatures: [
Expand Down
16 changes: 10 additions & 6 deletions extensions/github1s/src/adapters/github1s/data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,13 +325,15 @@ export class GitHub1sDataSource extends DataSource {
createTime: new Date(item.created_at),
mergeTime: item.merged_at ? new Date(item.merged_at) : null,
closeTime: item.closed_at ? new Date(item.closed_at) : null,
head: { label: item.head.label, commitSha: item.head.sha },
base: { label: item.base.label, commitSha: item.base.sha },
source: item.base.label,
target: item.head.label,
sourceSha: item.base.sha,
targetSha: item.head.sha,
avatarUrl: item.user?.avatar_url,
}));
}

async provideCodeReview(repoFullName: string, id: string): Promise<CodeReview & { files?: ChangedFile[] }> {
async provideCodeReview(repoFullName: string, id: string) {
const fetcher = GitHubFetcher.getInstance();
const { owner, repo } = parseRepoFullName(repoFullName);
const pullRequestParams = { owner, repo, pull_number: Number(id) };
Expand All @@ -345,8 +347,10 @@ export class GitHub1sDataSource extends DataSource {
createTime: new Date(data.created_at),
mergeTime: data.merged_at ? new Date(data.merged_at) : null,
closeTime: data.closed_at ? new Date(data.closed_at) : null,
head: { label: data.head.label, commitSha: data.head.sha },
base: { label: data.base.label, commitSha: data.base.sha },
source: data.base.label,
target: data.head.label,
sourceSha: data.base.sha,
targetSha: data.head.sha,
avatarUrl: data.user?.avatar_url,
};
}
Expand Down Expand Up @@ -426,6 +430,6 @@ export class GitHub1sDataSource extends DataSource {
}

provideUserAvatarLink(user: string): string {
return `https://github.com/${user}.png`;
return `${GITHUB_ORIGIN}/${user}.png`;
}
}
7 changes: 3 additions & 4 deletions extensions/github1s/src/adapters/github1s/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export class GitHubFetcher {
// initial fetcher methods in this way for correct `request/graphql` type inference
initFetcherMethods() {
const accessToken = GitHubTokenManager.getInstance().getToken();
const octokit = new Octokit({ auth: accessToken, request: { fetch } });
const octokit = new Octokit({ auth: accessToken, request: { fetch }, baseUrl: GITHUB_API_PREFIX });

this._originalRequest = octokit.request;
this.request = Object.assign((...args: Parameters<Octokit['request']>) => {
Expand All @@ -93,9 +93,8 @@ export class GitHubFetcher {
}, this._originalRequest);

this.graphql = Object.assign(async (...args: Parameters<Octokit['graphql']>) => {
// graphql API only worked for authenticated users
if (!GitHubTokenManager.getInstance().getToken()) {
const message = 'GraphQL API only worked for authenticated users';
const message = 'GraphQL API only works for authenticated users';
await GitHub1sAuthenticationView.getInstance().open(message, true);
}
return octokit.graphql(...args);
Expand All @@ -119,7 +118,7 @@ export class GitHubFetcher {
const response = await this._originalRequest?.('GET /repos/{owner}/{repo}', { owner, repo });
response?.data?.private && (await this.setUseSourcegraphApiFirst(false));
return response?.data || null;
})).then(() => null);
})).catch(() => null);
}

public async useSourcegraphApiFirst(repo?: string): Promise<boolean> {
Expand Down
2 changes: 1 addition & 1 deletion extensions/github1s/src/adapters/github1s/parse-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ const parsePullUrl = async (path: string): Promise<RouterState> => {
return {
repo: `${owner}/${repo}`,
pageType: PageType.CodeReview,
ref: codeReview.head.commitSha,
ref: codeReview.targetSha,
codeReviewId,
};
};
Expand Down
3 changes: 2 additions & 1 deletion extensions/github1s/src/adapters/github1s/router-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* @author netcon
*/

import { joinPath } from '@/helpers/util';
import * as adapterTypes from '../types';
import { parseGitHubPath } from './parse-path';

Expand Down Expand Up @@ -46,6 +47,6 @@ export class GitHub1sRouterParser extends adapterTypes.RouterParser {
}

buildExternalLink(path: string): string {
return 'https://github.com' + (path.startsWith('/') ? path : `/${path}`);
return joinPath(GITHUB_ORIGIN, path);
}
}
2 changes: 1 addition & 1 deletion extensions/github1s/src/adapters/github1s/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class GitHub1sSettingsViewProvider implements vscode.WebviewViewProvider
'For API requests using Authentication, you can make up to 5,000 requests per hour.',
],
OAuthButtonText: 'Connect to GitHub',
createTokenLink: 'https://github.com/settings/tokens/new?scopes=repo&description=GitHub1s',
createTokenLink: `${GITHUB_ORIGIN}/settings/tokens/new?scopes=repo&description=GitHub1s`,
};

public registerListeners(webviewView: vscode.WebviewView) {
Expand Down
2 changes: 1 addition & 1 deletion extensions/github1s/src/adapters/github1s/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class GitHubTokenManager {
return Promise.resolve(null);
}
const fetchOptions = accessToken ? { headers: { Authorization: `token ${accessToken}` } } : {};
return fetch('https://api.github.com/user', fetchOptions)
return fetch(`${GITHUB_API_PREFIX}/user`, fetchOptions)
.then((response) => {
if (response.status === 401) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class GitLab1sAuthenticationView extends GitHub1sAuthenticationView {
authenticationFormTitle: 'Authenticating to GitLab',
OAuthButtonText: 'Connect to GitLab',
OAuthButtonLogo: 'assets/pages/assets/gitlab.svg',
createTokenLink: 'https://gitlab.com/-/profile/personal_access_tokens?scopes=read_api&name=GitLab1s',
createTokenLink: `${GITLAB_ORIGIN}/-/profile/personal_access_tokens?scopes=read_api&name=GitLab1s`,
authenticationFeatures: [
{
text: 'Access GitLab personal repository',
Expand Down
42 changes: 20 additions & 22 deletions extensions/github1s/src/adapters/gitlab1s/data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,16 @@ const FileTypeMap = {
commit: FileType.Submodule,
};

const getPullState = (pull: { state: string; merged_at: string | null }): CodeReviewState => {
// current pull request is open
if (pull.state === 'opened') {
const getMergeRequestState = (mergeRequest: { state: string; merged_at: string | null }): CodeReviewState => {
// current merge request is open
if (mergeRequest.state === 'opened') {
return CodeReviewState.Open;
}
// current pull request is merged
if (pull.state === 'closed' && pull.merged_at) {
// current merge request is merged
if (mergeRequest.state === 'closed' && mergeRequest.merged_at) {
return CodeReviewState.Merged;
}
// current pull is closed
// current merge is closed
return CodeReviewState.Merged;
};

Expand Down Expand Up @@ -141,7 +141,6 @@ export class GitLab1sDataSource extends DataSource {
name: item.name,
commitSha: item.commit.id,
description: `${ref === 'heads' ? 'Branch' : 'Tag'} at ${item.commit.short_id}`,
isDefault: item.default,
}));
}

Expand Down Expand Up @@ -332,33 +331,34 @@ export class GitLab1sDataSource extends DataSource {
return data.map((item) => ({
id: `${item.iid}`,
title: item.title,
state: getPullState(item),
state: getMergeRequestState(item),
creator: item.author?.name || item.author?.username,
createTime: new Date(item.created_at),
// Some versions do not have a merged_at field
mergeTime: item.merged_at ? new Date(item.merged_at) : item.updated_at ? new Date(item.updated_at) : null,
mergeTime: item.merged_at ? new Date(item.merged_at) : null,
closeTime: item.closed_at ? new Date(item.closed_at) : null,
head: { label: item.labels[0], commitSha: item.sha },
base: { label: item.labels[1], commitSha: '' }, // Populated when getting changes
source: item.source_branch,
target: item.target_branch,
avatarUrl: item.author?.avatar_url,
}));
}

async provideCodeReview(repo: string, id: string): Promise<CodeReview & { files?: ChangedFile[] }> {
async provideCodeReview(repo: string, id: string) {
const fetcher = GitLabFetcher.getInstance();
const pullRequestParams = { repo, pull_number: Number(id) };
const { data } = await fetcher.request('GET /projects/{repo}/merge_requests/{pull_number}', pullRequestParams);
const requestParams = { repo, id };
const { data } = await fetcher.request('GET /projects/{repo}/merge_requests/{id}', requestParams);

return {
id: `${data.iid}`,
title: data.title,
state: getPullState(data),
state: getMergeRequestState(data),
creator: data.author?.name || data.author?.username,
createTime: new Date(data.created_at),
mergeTime: data.merged_at ? new Date(data.merged_at) : null,
closeTime: data.closed_at ? new Date(data.closed_at) : null,
head: { label: data.labels[0], commitSha: data.diff_refs.head_sha },
base: { label: data.labels[1], commitSha: data.diff_refs.base_sha },
source: data.source_branch,
target: data.target_branch,
sourceSha: data.diff_refs.base_sha,
targetSha: data.diff_refs.head_sha,
avatarUrl: data.author?.avatar_url,
};
}
Expand All @@ -367,9 +367,9 @@ export class GitLab1sDataSource extends DataSource {
async provideCodeReviewChangedFiles(repo: string, id: string, options?: CommonQueryOptions): Promise<ChangedFile[]> {
const fetcher = GitLabFetcher.getInstance();
const pageParams = { per_page: options?.pageSize, page: options?.page };
const filesRequestParams = { repo, pull_number: Number(id), ...pageParams };
const filesRequestParams = { repo, id, ...pageParams };
const { data } = await fetcher.request(
'GET /projects/{repo}/merge_requests/{pull_number}/changes?per_page={per_page}&page={page}',
'GET /projects/{repo}/merge_requests/{id}/changes?per_page={per_page}&page={page}',
filesRequestParams
);

Expand All @@ -383,8 +383,6 @@ export class GitLab1sDataSource extends DataSource {
: item.renamed_file
? FileChangeStatus.Renamed
: FileChangeStatus.Modified,
head: data.diff_refs.head_sha,
base: data.diff_refs.base_sha,
}));
}

Expand Down
2 changes: 1 addition & 1 deletion extensions/github1s/src/adapters/gitlab1s/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class GitLabFetcher {
accessToken?.length < 60
? { headers: { 'PRIVATE-TOKEN': `${accessToken}` } }
: { headers: { Authorization: `Bearer ${accessToken}` } };
return fetch(`${GITLAB_DOMAIN}/api/v4` + path, {
return fetch(GITLAB_API_PREFIX + path, {
...fetchOptions,
method,
}).then(async (response: Response & { data: any }) => {
Expand Down
2 changes: 1 addition & 1 deletion extensions/github1s/src/adapters/gitlab1s/parse-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ const parseMergeRequestUrl = async (path: string): Promise<RouterState> => {
return {
repo: `${owner}/${repo}`,
pageType: PageType.CodeReview,
ref: codeReview.base.commitSha,
ref: codeReview.targetSha,
codeReviewId,
};
};
Expand Down
3 changes: 2 additions & 1 deletion extensions/github1s/src/adapters/gitlab1s/router-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* @author netcon
*/

import { joinPath } from '@/helpers/util';
import * as adapterTypes from '../types';
import { parseGitLabPath } from './parse-path';

Expand Down Expand Up @@ -46,6 +47,6 @@ export class GitLab1sRouterParser extends adapterTypes.RouterParser {
}

buildExternalLink(path: string): string {
return GITLAB_DOMAIN + (path.startsWith('/') ? path : `/${path}`);
return joinPath(GITLAB_ORIGIN, path);
}
}
2 changes: 1 addition & 1 deletion extensions/github1s/src/adapters/gitlab1s/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ export class GitLab1sSettingsViewProvider extends GitHub1sSettingsViewProvider {
"Your token will only be stored locally in your browser. Don't forget to clean it while you are using a public device.",
],
OAuthButtonText: 'Connect to GitLab',
createTokenLink: 'https://gitlab.com/-/profile/personal_access_tokens?scopes=read_api&name=GitLab1s',
createTokenLink: `${GITLAB_ORIGIN}/-/profile/personal_access_tokens?scopes=read_api&name=GitLab1s`,
};
}
2 changes: 1 addition & 1 deletion extensions/github1s/src/adapters/gitlab1s/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class GitLabTokenManager extends GitHubTokenManager {
accessToken?.length < 60
? { headers: { 'PRIVATE-TOKEN': `${accessToken}` } }
: { headers: { Authorization: `Bearer ${accessToken}` } };
return fetch(`${GITLAB_DOMAIN}/api/v4/user`, fetchOptions)
return fetch(`${GITLAB_API_PREFIX}/user`, fetchOptions)
.then((response) => {
if (response.status === 401) {
return null;
Expand Down
3 changes: 1 addition & 2 deletions extensions/github1s/src/adapters/sourcegraph/data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ export class SourcegraphDataSource extends DataSource {
return `github.com/${repo}`;
}
if (this.platform === 'gitlab') {
// return `gitlab.com/${repo}`;
return `${GITLAB_DOMAIN.replace('https://', '')}/${repo}`;
return `gitlab.com/${repo}`;
}
if (this.platform === 'bitbucket') {
return `bitbucket.org/${repo}`;
Expand Down
22 changes: 9 additions & 13 deletions extensions/github1s/src/adapters/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ export interface Branch {
name: string;
commitSha?: string;
description?: string;
isDefault?: boolean;
}

export interface Tag {
Expand Down Expand Up @@ -127,14 +126,10 @@ export interface CodeReview {
createTime: Date;
mergeTime: Date | null;
closeTime: Date | null;
head: {
label: string;
commitSha: string;
};
base: {
label: string;
commitSha: string;
};
source: string;
target: string;
sourceSha?: string;
targetSha?: string;
avatarUrl?: string;
}

Expand All @@ -151,8 +146,6 @@ export interface ChangedFile {
path: string;
// only exists for renamed file
previousPath?: string;
head?: string;
base?: string;
}

export interface BlameRange {
Expand Down Expand Up @@ -241,7 +234,10 @@ export class DataSource {
}

// optionally return changed files (if `files` exists can reduce api calls)
provideCodeReview(repo: string, id: string): Promisable<(CodeReview & { files?: ChangedFile[] }) | null> {
provideCodeReview(
repo: string,
id: string
): Promisable<(CodeReview & { sourceSha: string; targetSha: string; files?: ChangedFile[] }) | null> {
return null;
}

Expand Down Expand Up @@ -384,7 +380,7 @@ export class RouterParser {

// convert giving path to the external link (using for jumping back to origin platform)
buildExternalLink(path: string): Promisable<string> {
return 'https://github.com' + path;
return path;
}
}

Expand Down
Loading

0 comments on commit 2189398

Please sign in to comment.