1 | import urlJoin from 'url-join';
|
2 |
|
3 | function normalizeRawRepository({
|
4 | rawRepository
|
5 | }) {
|
6 | if (isRepository(rawRepository)) {
|
7 | return normalizeRepository({
|
8 | rawRepository
|
9 | });
|
10 | }
|
11 |
|
12 | if (typeof rawRepository === 'string') {
|
13 | return normalizeRepository({
|
14 | rawRepository: {
|
15 | url: rawRepository
|
16 | }
|
17 | });
|
18 | }
|
19 |
|
20 | return undefined;
|
21 | }
|
22 |
|
23 | function isRepository(rawRepository) {
|
24 | return rawRepository && typeof rawRepository === 'object' && typeof rawRepository['url'] === 'string' && ['string', 'undefined'].includes(typeof rawRepository['type']) && ['string', 'undefined'].includes(typeof rawRepository['directory']);
|
25 | }
|
26 |
|
27 | function normalizeRepository({
|
28 | rawRepository
|
29 | }) {
|
30 | const {
|
31 | url,
|
32 | directory
|
33 | } = rawRepository;
|
34 | const parsedUrl = parseGitURL({
|
35 | url
|
36 | });
|
37 |
|
38 | if (!parsedUrl) {
|
39 | return undefined;
|
40 | }
|
41 |
|
42 | return {
|
43 | type: 'git',
|
44 | url: parsedUrl,
|
45 | directory
|
46 | };
|
47 | }
|
48 |
|
49 | function parseGitURL({
|
50 | url
|
51 | }) {
|
52 | const urlWithProtocol = url.includes(':') ?
|
53 | url :
|
54 | url.includes('/') ? `github:${url}` :
|
55 | '';
|
56 |
|
57 | try {
|
58 | const {
|
59 | protocol,
|
60 | hostname,
|
61 | pathname
|
62 | } = new URL(urlWithProtocol);
|
63 | const cleanPathname = pathname.replace(/\.git$/, '');
|
64 |
|
65 | if (protocol === 'github:' || hostname === 'github.com') {
|
66 | return urlJoin('https://github.com', cleanPathname);
|
67 | }
|
68 |
|
69 | if (protocol === 'gist:' || hostname === 'gist.github.com') {
|
70 | return urlJoin('https://gist.github.com', cleanPathname);
|
71 | }
|
72 |
|
73 | if (protocol === 'bitbucket:' || hostname === 'bitbucket.org') {
|
74 | return urlJoin('https://bitbucket.org', cleanPathname);
|
75 | }
|
76 |
|
77 | if (protocol === 'gitlab:' || hostname === 'gitlab.com') {
|
78 | return urlJoin('https://gitlab.com', cleanPathname);
|
79 | }
|
80 |
|
81 | return urlWithProtocol;
|
82 | } catch {
|
83 | return undefined;
|
84 | }
|
85 | }
|
86 |
|
87 | export { normalizeRawRepository };
|
88 |
|