-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgithub.svelte.ts
More file actions
238 lines (218 loc) · 8.47 KB
/
Copy pathgithub.svelte.ts
File metadata and controls
238 lines (218 loc) · 8.47 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
import { browser } from "$app/environment";
import type { components } from "@octokit/openapi-types";
import { parseMultiFilePatch, trimCommitHash } from "$lib/util";
import { LoadingState, makeImageDetails } from "$lib/diff-viewer-multi-file.svelte";
import { PUBLIC_GITHUB_APP_NAME, PUBLIC_GITHUB_CLIENT_ID } from "$env/static/public";
export const GITHUB_USERNAME_KEY = "github_username";
export const GITHUB_TOKEN_KEY = "github_token";
export const GITHUB_TOKEN_EXPIRES_KEY = "github_token_expires";
export const GITHUB_URL_PARAM = "github_url";
export const githubUsername: { value: string | null } = $state({ value: null });
export type GithubDiff = {
owner: string;
repo: string;
base: string;
head: string;
description: string;
backlink: string;
};
export type GithubDiffResult = {
info: Promise<GithubDiff>;
response: Promise<string>;
};
if (browser) {
githubUsername.value = localStorage.getItem(GITHUB_USERNAME_KEY);
}
export function getGithubUsername(): string | null {
return githubUsername.value;
}
export function getGithubToken(): string | null {
const expiresAt = localStorage.getItem(GITHUB_TOKEN_EXPIRES_KEY);
if (expiresAt !== null) {
const expiresIn = parseInt(expiresAt) - Date.now();
if (expiresIn <= 0) {
logoutGithub();
return null;
}
}
return localStorage.getItem(GITHUB_TOKEN_KEY);
}
export function loginWithGithub() {
if (getGithubUsername()) {
return;
}
localStorage.setItem("authReferrer", window.location.pathname);
const params = new URLSearchParams({
client_id: PUBLIC_GITHUB_CLIENT_ID,
redirect_uri: window.location.origin + "/github-callback",
});
window.location.href = "https://github.com/login/oauth/authorize?" + params.toString();
}
export function logoutGithub() {
localStorage.removeItem(GITHUB_TOKEN_KEY);
localStorage.removeItem(GITHUB_TOKEN_EXPIRES_KEY);
localStorage.removeItem(GITHUB_USERNAME_KEY);
githubUsername.value = null;
}
export function installGithubApp() {
localStorage.setItem("authReferrer", window.location.href);
window.location.href = `https://github.com/apps/${PUBLIC_GITHUB_APP_NAME}/installations/new`;
}
export type GithubPR = components["schemas"]["pull-request"];
export type FileStatus = "added" | "removed" | "modified" | "renamed" | "renamed_modified";
export type GithubUser = components["schemas"]["private-user"];
export type GithubCommitDetails = components["schemas"]["commit"];
export type GithubTokenResponse = {
access_token: string;
token_type: string;
scope: string;
expires_in: number;
};
export async function fetchGithubUserToken(code: string): Promise<GithubTokenResponse> {
const response = await fetch(new URL(`${window.location.origin}/github-token?code=${code}`), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
return await response.json();
} else {
throw Error(`Failed to retrieve token (${response.status}): ${await response.text()}`);
}
}
export async function fetchCurrentGithubUser(token: string): Promise<GithubUser> {
const response = await fetch(`https://api.github.com/user`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
return await response.json();
} else {
throw Error(`Failed to retrieve user (${response.status}): ${await response.text()}`);
}
}
export async function fetchGithubPRComparison(token: string | null, owner: string, repo: string, prNumber: string): Promise<GithubDiffResult> {
const prInfo = await fetchGithubPRInfo(token, owner, repo, prNumber);
const base = prInfo.base.sha;
const head = prInfo.head.sha;
const title = `${prInfo.title} (#${prInfo.number})`;
return fetchGithubComparison(token, owner, repo, base, head, title, prInfo.html_url);
}
function injectOptionalToken(token: string | null, opts: RequestInit) {
if (token) {
opts.headers = {
...opts.headers,
Authorization: `Bearer ${token}`,
};
}
}
async function fetchGithubPRInfo(token: string | null, owner: string, repo: string, prNumber: string): Promise<GithubPR> {
const opts: RequestInit = {
headers: {
Accept: "application/json",
},
};
injectOptionalToken(token, opts);
const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}`, opts);
if (response.ok) {
return await response.json();
} else {
throw Error(`Failed to retrieve PR info (${response.status}): ${await response.text()}`);
}
}
export function parseMultiFilePatchGithub(details: GithubDiff, patch: string, loadingState: LoadingState) {
return parseMultiFilePatch(patch, loadingState, (from, to, status) => {
const token = getGithubToken();
return makeImageDetails(
from,
to,
status,
status != "added" ? fetchGithubFile(token, details.owner, details.repo, from, details.base) : undefined,
status != "removed" ? fetchGithubFile(token, details.owner, details.repo, to, details.head) : undefined,
);
});
}
export function fetchGithubComparison(
token: string | null,
owner: string,
repo: string,
base: string,
head: string,
description?: string,
url?: string,
): GithubDiffResult {
return {
info: (async () => {
if (!url) {
url = `https://github.com/${owner}/${repo}/compare/${base}...${head}`;
}
if (!description) {
description = `Comparing ${trimCommitHash(base)}...${trimCommitHash(head)}`;
}
return { owner, repo, base, head, description, backlink: url };
})(),
response: (async () => {
const opts: RequestInit = {
headers: {
Accept: "application/vnd.github.v3.diff",
},
};
injectOptionalToken(token, opts);
const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/compare/${base}...${head}`, opts);
if (!response.ok) {
throw Error(`Failed to retrieve comparison (${response.status}): ${await response.text()}`);
}
return await response.text();
})(),
};
}
export function fetchGithubCommitDiff(token: string | null, owner: string, repo: string, commit: string): GithubDiffResult {
const url = `https://api.github.com/repos/${owner}/${repo}/commits/${commit}`;
return {
info: (async () => {
const metaOpts: RequestInit = {
headers: {
Accept: "application/vnd.github+json",
},
};
injectOptionalToken(token, metaOpts);
const metaResponse = await fetch(url, metaOpts);
if (!metaResponse.ok) {
throw Error(`Failed to retrieve commit meta (${metaResponse.status}): ${await metaResponse.text()}`);
}
const meta: GithubCommitDetails = await metaResponse.json();
const firstParent = meta.parents[0].sha;
const description = `${meta.commit.message.split("\n")[0]} (${trimCommitHash(commit)})`;
return { owner, repo, base: firstParent, head: commit, description, backlink: meta.html_url };
})(),
response: (async () => {
const diffOpts: RequestInit = {
headers: {
Accept: "application/vnd.github.v3.diff",
},
};
injectOptionalToken(token, diffOpts);
const response = await fetch(url, diffOpts);
if (!response.ok) {
throw Error(`Failed to retrieve commit diff (${response.status}): ${await response.text()}`);
}
return await response.text();
})(),
};
}
export async function fetchGithubFile(token: string | null, owner: string, repo: string, path: string, ref: string): Promise<Blob> {
const opts: RequestInit = {
headers: {
Accept: "application/vnd.github.v3.raw",
},
};
injectOptionalToken(token, opts);
const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${ref}`, opts);
if (response.ok) {
return await response.blob();
} else {
throw Error(`Failed to retrieve file (${response.status}): ${await response.text()}`);
}
}