forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithubGit.ts
More file actions
333 lines (317 loc) · 12 KB
/
Copy pathgithubGit.ts
File metadata and controls
333 lines (317 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { IGit, Repository, InputBox, RepositoryState, RepositoryUIState, Change, Branch, Ref, BranchQuery, Commit, LogOptions, CommitOptions, RefType } from '../api/api';
import { APIState } from '../typings/git';
import { CredentialStore, GitHub } from '../github/credentials';
import { OctokitResponse, ReposGetResponseData, ReposGetBranchResponseData } from '@octokit/types';
import { PullRequestGitHelper } from '../github/pullRequestGitHelper';
interface OctokitTreeResponse {
tree: {
path: string,
mode: string,
type: 'blob' | 'tree',
size?: number,
sha: string,
url: string
}[];
}
interface OctokitBlobResponse {
content: string;
encoding: 'base64';
url: string;
sha: string;
size: number;
}
class GithubGitRepository implements Repository {
inputBox: InputBox;
state: RepositoryState;
ui: RepositoryUIState;
constructor(public rootUri: vscode.Uri,
private _github: GitHub,
private _owner: string,
private _repo: string,
_repository: OctokitResponse<ReposGetResponseData>,
private _branch: OctokitResponse<ReposGetBranchResponseData>) {
const remote = {
name: 'origin',
fetchUrl: _repository.data.git_url,
isReadOnly: _branch.data.protected
};
this.state = {
HEAD: {
type: RefType.Head,
commit: _branch.data.commit.sha,
name: _branch.data.name,
upstream: {
name: remote.name,
remote: remote.name
}
},
indexChanges: [],
mergeChanges: [],
onDidChange: new vscode.EventEmitter<void>().event,
rebaseCommit: undefined,
refs: [],
remotes: [remote],
submodules: [],
workingTreeChanges: []
};
}
async getConfigs(): Promise<{ key: string; value: string; }[]> {
return [];
}
async getConfig(key: string): Promise<string> {
if (key === PullRequestGitHelper.getMetadataKeyForBranch(this._branch.data.name)) {
const pulls = await this._github.octokit.pulls.list({ owner: this._owner, repo: this._repo, head: `${this._owner}:${this._branch.data.name}` });
if (pulls.data.length > 0) {
return `${this._owner}#${this._repo}#${pulls.data[0].number}`;
}
}
return '';
}
async setConfig(key: string, value: string): Promise<string> {
return '';
}
getGlobalConfig(key: string): Promise<string> {
// Not used in extension
throw new Error('Method not implemented.');
}
async getObjectDetails(treeish: string, path: string): Promise<{ mode: string; object: string; size: number; }> {
const fsPath = vscode.Uri.file(path).fsPath;
const itemPath = fsPath.startsWith('/') ? fsPath.substr(1) : fsPath.startsWith('\\') ? fsPath.substr(1) : fsPath;
const treeResponse: OctokitTreeResponse = (await this.requestTrees(treeish)).data;
for (const item of treeResponse.tree) {
if (itemPath) {
if ((item.type === 'blob') && ((item.path === itemPath) || vscode.Uri.joinPath(this.rootUri, item.path).fsPath === fsPath)) {
return { mode: item.type, object: item.sha, size: item.size ?? 0 };
}
} else if (item.type === 'tree') {
return { mode: item.type, object: item.sha, size: 0 };
}
}
throw new Error('treeish or path not found');
}
async detectObjectType(object: string): Promise<{ mimetype: string; encoding?: string | undefined; }> {
// No API for detecting a blob type, so only text/plain currently supported.
return { mimetype: 'text/plain' };
}
buffer(ref: string, path: string): Promise<Buffer> {
// Currently only used when detectObjectType return something other than text/plain.
throw new Error('Method not implemented.');
}
async show(ref: string, path: string): Promise<string> {
try {
const objectDetails = await this.getObjectDetails(ref, path);
const blobResponse: OctokitBlobResponse = (await this.requestBlobs(objectDetails.object)).data;
return Buffer.from(blobResponse.content, 'base64').toString();
} catch (e) {
throw new Error('treeish or path not found');
}
}
async getCommit(ref: string): Promise<Commit> {
const commit = await this._github.octokit.repos.getCommit({ owner: this._owner, repo: this._repo, ref });
return {
hash: commit.data.sha,
parents: commit.data.parents.map(parent => {
return parent.sha;
}),
message: commit.data.commit.message
};
}
clean(paths: string[]): Promise<void> {
// Not used in extension
throw new Error('Method not implemented.');
}
apply(patch: string, reverse?: boolean | undefined): Promise<void> {
throw new Error('Method not implemented.');
}
diff(cached?: boolean | undefined): Promise<string> {
throw new Error('Method not implemented.');
}
diffWithHEAD(): Promise<Change[]>;
diffWithHEAD(path: string): Promise<string>;
diffWithHEAD(path?: any): any {
if (path) {
return '';
}
throw new Error('Method not implemented.');
}
diffWith(ref: string): Promise<Change[]>;
diffWith(ref: string, path: string): Promise<string>;
diffWith(ref: any, path?: any): any {
// Not used in extension
throw new Error('Method not implemented.');
}
diffIndexWithHEAD(): Promise<Change[]>;
diffIndexWithHEAD(path: string): Promise<string>;
diffIndexWithHEAD(path?: any): any {
// Not used in extension
throw new Error('Method not implemented.');
}
diffIndexWith(ref: string): Promise<Change[]>;
diffIndexWith(ref: string, path: string): Promise<string>;
diffIndexWith(ref: any, path?: any): any {
// Not used in extension
throw new Error('Method not implemented.');
}
diffBlobs(object1: string, object2: string): Promise<string> {
throw new Error('Method not implemented.');
}
diffBetween(ref1: string, ref2: string): Promise<Change[]>;
diffBetween(ref1: string, ref2: string, path: string): Promise<string>;
diffBetween(ref1: any, ref2: any, path?: any): any {
throw new Error('Method not implemented.');
}
hashObject(data: string): Promise<string> {
throw new Error('Method not implemented.');
}
createBranch(name: string, checkout: boolean, ref?: string | undefined): Promise<void> {
throw new Error('Method not implemented.');
}
deleteBranch(name: string, force?: boolean | undefined): Promise<void> {
throw new Error('Method not implemented.');
}
async getBranch(name: string): Promise<Branch> {
const branch = await this._github.octokit.repos.getBranch({ owner: this._owner, repo: this._repo, branch: name });
return {
type: RefType.Head,
commit: branch.data.commit.sha,
name,
remote: this.state.remotes[0].name,
upstream: {
name: this.state.remotes[0].name,
remote: branch.data._links.html
}
};
}
async getBranches(query: BranchQuery): Promise<Ref[]> {
// There is no good way to accomplish this with the available API.
return [];
}
setBranchUpstream(name: string, upstream: string): Promise<void> {
throw new Error('Method not implemented.');
}
getMergeBase(ref1: string, ref2: string): Promise<string> {
// Not used in extension
throw new Error('Method not implemented.');
}
status(): Promise<void> {
throw new Error('Method not implemented.');
}
checkout(treeish: string): Promise<void> {
throw new Error('Method not implemented.');
}
addRemote(name: string, url: string): Promise<void> {
throw new Error('Method not implemented.');
}
removeRemote(name: string): Promise<void> {
throw new Error('Method not implemented.');
}
renameRemote(name: string, newName: string): Promise<void> {
throw new Error('Method not implemented.');
}
async fetch(remote?: string | undefined, ref?: string | undefined, depth?: number | undefined): Promise<void> {
// Fetch doesn't mean anything because we aren't paying attention to the file system.
}
async pull(unshallow?: boolean | undefined): Promise<void> {
// Pull doesn't mean anything because we aren't paying attention to the file system.
}
push(remoteName?: string | undefined, branchName?: string | undefined, setUpstream?: boolean | undefined): Promise<void> {
throw new Error('Method not implemented.');
}
blame(path: string): Promise<string> {
throw new Error('Method not implemented.');
}
async log(options?: LogOptions | undefined): Promise<Commit[]> {
if (!options || !options.maxEntries || (options.maxEntries !== 1) || !options.path) {
throw new Error('Log options are required with GitHub git provider.');
}
const branch = await this.getBranch(this._branch.data.name);
if (branch.commit) {
return [await this.getCommit(branch.commit)];
}
return [];
}
commit(message: string, opts?: CommitOptions | undefined): Promise<void> {
throw new Error('Method not implemented.');
}
private async requestTrees(tree_sha: string): Promise<OctokitResponse<OctokitTreeResponse>> {
return this._github.octokit.request('GET /repos/{owner}/{repo}/git/trees/{tree_sha}', {
owner: this._owner,
repo: this._repo,
tree_sha: tree_sha
});
}
private async requestBlobs(tree_sha: string): Promise<OctokitResponse<OctokitBlobResponse>> {
return this._github.octokit.request('GET /repos/{owner}/{repo}/git/blobs/{tree_sha}', {
owner: this._owner,
repo: this._repo,
tree_sha: tree_sha
});
}
}
export class GithubGitProvider implements IGit, vscode.Disposable {
get repositories(): Repository[] {
return Array.from(this._repositories.values());
}
get state(): APIState {
return this._credentialStore.isAuthenticated() ? 'initialized' : 'uninitialized';
}
private _onDidOpenRepository = new vscode.EventEmitter<Repository>();
readonly onDidOpenRepository: vscode.Event<Repository> = this._onDidOpenRepository.event;
private _onDidCloseRepository = new vscode.EventEmitter<Repository>();
readonly onDidCloseRepository: vscode.Event<Repository> = this._onDidCloseRepository.event;
private _onDidChangeState = new vscode.EventEmitter<APIState>();
readonly onDidChangeState: vscode.Event<APIState> = this._onDidChangeState.event;
private _repositories: Map<string, Repository> = new Map();
private _disposables: vscode.Disposable[];
constructor(private _credentialStore: CredentialStore) {
this._disposables = [];
this.findRepos();
}
private async findRepos() {
if (this._credentialStore.isAuthenticated()) {
const folders = vscode.workspace.workspaceFolders ?? [];
const hub = this._credentialStore.getHub();
if (!hub) {
return;
}
for (const folder of folders) {
// If the scheme is codespace, then the authority will indicate the repository.
if (folder.uri.scheme !== 'codespace') {
continue;
}
const match = folder.uri.authority.match(/^([A-Za-z0-9_\.-]+)\+([A-Za-z0-9_\.-]+)(\+([A-Za-z0-9_\.-]+))?$/);
if (!match || match.length !== 5) {
continue;
}
const owner = match[1];
const repo = match[2];
let branch = match[3];
const githubRepo = await hub.octokit.repos.get({ owner, repo });
if (!githubRepo) {
continue;
}
branch = branch ?? githubRepo.data.default_branch;
const githubBranch = await hub.octokit.repos.getBranch({ owner, repo, branch });
const openedRepository = new GithubGitRepository(folder.uri, hub, owner, repo, githubRepo, githubBranch);
this._repositories.set(`${owner}/${repo}`, openedRepository);
this._onDidOpenRepository.fire(openedRepository);
}
// If you can't test in codespaces, you can uncomment the following lines to test with a repo
// and branch of your choice.
// Repo should match the repo you actually have open if you don't want unexpected results.
// const repo = await hub.octokit.repos.get({ owner: 'alexr00', repo: 'playground' });
// const branch = await hub.octokit.repos.getBranch({ owner: 'alexr00', repo: 'playground', branch: 'testlowercase' });
// const openedRepository = new GithubGitRepository(vscode.workspace.workspaceFolders![0].uri, hub, 'alexr00', 'playground', repo, branch);
// this._repositories.set('alexr00/playground', openedRepository);
// this._onDidOpenRepository.fire(openedRepository);
}
}
dispose() {
this._disposables.forEach(disposable => disposable.dispose());
}
}