UNPKG

2.42 kBPlain TextView Raw
1import urlJoin from 'url-join';
2import { GitRepository } from '../types/git-repository';
3import { Repository } from '../types/repository';
4
5export 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
23function 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
33function normalizeRepository({
34 rawRepository,
35}: {
36 rawRepository: Repository;
37}): GitRepository | undefined {
38 const { url, directory } = rawRepository;
39
40 const parsedUrl = parseGitURL({ url });
41 if (!parsedUrl) {
42 return undefined;
43 }
44
45 return {
46 type: 'git',
47 url: parsedUrl,
48 directory,
49 };
50}
51
52function parseGitURL({ url }: { url: string }): string | undefined {
53 const urlWithProtocol = url.includes(':')
54 ? // A normal URL or a shortcut like `github:user/repository`
55 url
56 : // The short form github shortcut `user/repository`
57 url.includes('/')
58 ? `github:${url}`
59 : // Not a URL
60 '';
61 try {
62 const { protocol, hostname, pathname } = new URL(urlWithProtocol);
63 const cleanPathname = pathname.replace(/\.git$/, '');
64 if (protocol === 'github:' || hostname === 'github.com') {
65 return urlJoin('https://github.com', cleanPathname);
66 }
67 if (protocol === 'gist:' || hostname === 'gist.github.com') {
68 return urlJoin('https://gist.github.com', cleanPathname);
69 }
70 if (protocol === 'bitbucket:' || hostname === 'bitbucket.org') {
71 return urlJoin('https://bitbucket.org', cleanPathname);
72 }
73 if (protocol === 'gitlab:' || hostname === 'gitlab.com') {
74 return urlJoin('https://gitlab.com', cleanPathname);
75 }
76 return urlWithProtocol;
77 } catch {
78 return undefined;
79 }
80}