1 | import gitUrlParse from 'git-url-parse';
|
2 | import { GitRepository } from '../types/git-repository';
|
3 | import { Repository } from '../types/repository';
|
4 |
|
5 | export function normalizeRawRepository({
|
6 | rawRepository,
|
7 | }: {
|
8 | rawRepository?: any;
|
9 | }): GitRepository | undefined {
|
10 | if (isRepository(rawRepository)) {
|
11 | return normalizeRepository({ rawRepository });
|
12 | }
|
13 |
|
14 | if (typeof rawRepository === 'string') {
|
15 | return normalizeRepository({
|
16 | rawRepository: { url: rawRepository },
|
17 | });
|
18 | }
|
19 |
|
20 | return undefined;
|
21 | }
|
22 |
|
23 | function isRepository(rawRepository: any): rawRepository is Repository {
|
24 | return (
|
25 | rawRepository &&
|
26 | typeof rawRepository === 'object' &&
|
27 | typeof rawRepository['url'] === 'string' &&
|
28 | ['string', 'undefined'].includes(typeof rawRepository['type']) &&
|
29 | ['string', 'undefined'].includes(typeof rawRepository['directory'])
|
30 | );
|
31 | }
|
32 |
|
33 | function normalizeRepository({
|
34 | rawRepository,
|
35 | }: {
|
36 | rawRepository: Repository;
|
37 | }): GitRepository | undefined {
|
38 | const { url, directory: repositoryDir } = rawRepository;
|
39 |
|
40 | const info = parseGitURL({ url });
|
41 | if (!info) {
|
42 | return undefined;
|
43 | }
|
44 |
|
45 | const { resource, full_name: repositoryID, filepath } = info;
|
46 |
|
47 |
|
48 | const host = resource
|
49 | .replace(/^$/, 'github.com')
|
50 | .replace(/^github$/, 'github.com')
|
51 | .replace(/^gitlab$/, 'gitlab.com')
|
52 | .replace(/^bitbucket$/, 'bitbucket.org');
|
53 |
|
54 | const parsedDir = filepath !== '' ? filepath : undefined;
|
55 |
|
56 | return {
|
57 | type: 'git',
|
58 | url: `https://${host}/${repositoryID}`,
|
59 | directory: repositoryDir ?? parsedDir,
|
60 | };
|
61 | }
|
62 |
|
63 | function parseGitURL({ url }: { url: string }): gitUrlParse.GitUrl | undefined {
|
64 | let info;
|
65 | try {
|
66 | info = gitUrlParse(url);
|
67 | } catch {}
|
68 | return info;
|
69 | }
|