forked from download-directory/download-directory.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepository-info.ts
More file actions
106 lines (93 loc) · 2.38 KB
/
repository-info.ts
File metadata and controls
106 lines (93 loc) · 2.38 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
import authenticatedFetch from './authenticated-fetch.js';
function cleanUrl(url: string) {
return url
.replace(/[/]{2,}/, '/') // Drop double slashes
.replace(/[/]$/, ''); // Drop trailing slash
}
async function parsePath(
user: string,
repo: string,
parts: string[],
): Promise<{gitReference: string; directory: string} | void> {
for (let i = 0; i < parts.length; i++) {
const gitReference = parts.slice(0, i + 1).join('/');
// eslint-disable-next-line no-await-in-loop -- One at a time
if (await checkBranchExists(user, repo, gitReference)) {
return {
gitReference,
directory: parts.slice(i + 1).join('/'),
};
}
}
}
export default async function getRepositoryInfo(
url: string,
): Promise<
| {error: string}
| {
user: string;
repository: string;
gitReference?: string;
directory: string;
downloadUrl: string;
isPrivate: boolean;
}
| {
user: string;
repository: string;
gitReference: string;
directory: string;
isPrivate: boolean;
}
> {
const [, user, repository, type, ...parts] = cleanUrl(
decodeURIComponent(new URL(url).pathname),
).split('/');
if (!user || !repository) {
return {error: 'NOT_A_REPOSITORY'};
}
if (type && type !== 'tree') {
return {error: 'NOT_A_DIRECTORY'};
}
const repoInfoResponse = await authenticatedFetch(
`https://api.github.com/repos/${user}/${repository}`,
);
if (repoInfoResponse.status === 404) {
return {error: 'REPOSITORY_NOT_FOUND'};
}
const {private: isPrivate} = await repoInfoResponse.json() as {private: boolean};
if (parts.length === 0) {
return {
user,
repository,
directory: '',
isPrivate,
downloadUrl: `https://api.github.com/repos/${user}/${repository}/zipball`,
};
}
if (parts.length === 1) {
return {
user,
repository,
gitReference: parts[0],
directory: '',
isPrivate,
downloadUrl: `https://api.github.com/repos/${user}/${repository}/zipball/${parts[0]}`,
};
}
const parsedPath = await parsePath(user, repository, parts);
if (!parsedPath) {
return {error: 'BRANCH_NOT_FOUND'};
}
return {
user,
repository,
isPrivate,
...parsedPath,
};
}
async function checkBranchExists(user: string, repo: string, gitReference: string): Promise<boolean> {
const apiUrl = `https://api.github.com/repos/${user}/${repo}/commits/${gitReference}?per_page=1`;
const response = await authenticatedFetch(apiUrl, {method: 'HEAD'});
return response.ok;
}