UNPKG

1.9 kBJavaScriptView Raw
1const la = require('lazy-ass')
2const is = require('check-more-types')
3const parse = require('parse-github-repo-url')
4const url = require('url')
5
6function formHttpsGithubUrl (domain, user, repo) {
7 return `https://${domain}/${user}/${repo}.git`
8}
9
10function formHttpsGitlabUrl (domain, user, repo) {
11 return `https://${domain}/${user}/${repo}.git`
12}
13
14const isGithub = url => url.includes('github')
15const isGitlab = url => url.includes('gitlab')
16
17function isGitAt (url) {
18 return url.startsWith('git@')
19}
20
21// extracts domain from git@<domain>:...
22function getDomainFromGitAt (s) {
23 la(isGitAt(s), 'expected git@ remote url', s)
24 const from = s.indexOf('@')
25 const to = s.indexOf(':')
26 return s.substr(from + 1, to - from - 1)
27}
28
29// extracts domain from https://...
30function getDomainFromUrl (s) {
31 la(is.https(s), 'expected https:// url', s)
32 const parsed = url.parse(s)
33 return parsed.host
34}
35
36function getDomain (s) {
37 return isGitAt(s) ? getDomainFromGitAt(s) : getDomainFromUrl(s)
38}
39
40// transforms git ssh to https
41function gitRemoteToHttps (url) {
42 la(is.unemptyString(url), 'expected url string', url)
43 if (is.https(url)) {
44 return url
45 }
46
47 la(isGitAt(url), 'not git@ url', url)
48
49 const parsed = parse(url)
50 la(is.array(parsed), 'could not parse git url', url)
51 const user = parsed[0]
52 const repo = parsed[1]
53 la(is.unemptyString(user), 'could not get user from url', url)
54 la(is.unemptyString(repo), 'could not get repo from url', url)
55
56 const domain = getDomain(url)
57 la(is.unemptyString(domain), 'missing domain from url', url)
58
59 if (isGithub(url)) {
60 return formHttpsGithubUrl(domain, user, repo)
61 }
62 if (isGitlab(url)) {
63 return formHttpsGitlabUrl(domain, user, repo)
64 }
65
66 const msg = `Could not transform remote url ${url} into https:`
67 throw new Error(msg)
68}
69
70module.exports = {
71 isGitAt,
72 isGithub,
73 isGitlab,
74 gitRemoteToHttps,
75 getDomain
76}