/
index.ts
74 lines (67 loc) · 2.06 KB
/
index.ts
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
import { logger } from '../../../logger';
import { ExternalHostError } from '../../../types/errors/external-host-error';
import type { GitLabBranch } from '../../../types/platform/gitlab';
import { GitlabHttp } from '../../../util/http/gitlab';
import { Preset, PresetConfig } from '../common';
import { PRESET_DEP_NOT_FOUND, fetchPreset } from '../util';
const gitlabApi = new GitlabHttp();
export const Endpoint = 'https://gitlab.com/api/v4/';
async function getDefaultBranchName(
urlEncodedPkgName: string,
endpoint: string
): Promise<string> {
const branchesUrl = `${endpoint}projects/${urlEncodedPkgName}/repository/branches`;
const res = await gitlabApi.getJson<GitLabBranch[]>(branchesUrl);
const branches = res.body;
let defautlBranchName = 'master';
for (const branch of branches) {
if (branch.default) {
defautlBranchName = branch.name;
break;
}
}
return defautlBranchName;
}
export async function fetchJSONFile(
repo: string,
fileName: string,
endpoint: string
): Promise<Preset> {
try {
const urlEncodedRepo = encodeURIComponent(repo);
const urlEncodedPkgName = encodeURIComponent(fileName);
const defautlBranchName = await getDefaultBranchName(
urlEncodedRepo,
endpoint
);
const url = `${endpoint}projects/${urlEncodedRepo}/repository/files/${urlEncodedPkgName}/raw?ref=${defautlBranchName}`;
return (await gitlabApi.getJson<Preset>(url)).body;
} catch (err) {
if (err instanceof ExternalHostError) {
throw err;
}
logger.debug(
{ statusCode: err.statusCode },
`Failed to retrieve ${fileName} from repo`
);
throw new Error(PRESET_DEP_NOT_FOUND);
}
}
export async function getPresetFromEndpoint(
pkgName: string,
presetName: string,
endpoint = Endpoint
): Promise<Preset> {
return fetchPreset({
pkgName,
filePreset: presetName,
endpoint,
fetch: fetchJSONFile,
});
}
export function getPreset({
packageName: pkgName,
presetName = 'default',
}: PresetConfig): Promise<Preset> {
return getPresetFromEndpoint(pkgName, presetName, Endpoint);
}