UNPKG

2.82 kBJavaScriptView Raw
1'use strict'
2
3var url = require('url')
4var util = require('util')
5var isUrl = require('is-url')
6
7module.exports = function (repoUrl, opts) {
8 var obj = {}
9 opts = opts || {}
10
11 if (!repoUrl) return null
12
13 var shorthand = repoUrl.match(/^([\w-_]+)\/([\w-_\.]+)#?([\w-_\.]+)?$/)
14 var mediumhand = repoUrl.match(/^github:([\w-_]+)\/([\w-_\.]+)#?([\w-_\.]+)?$/)
15 var antiquated = repoUrl.match(/^git@[\w-_\.]+:([\w-_]+)\/([\w-_\.]+)$/)
16
17 if (shorthand) {
18 obj.user = shorthand[1]
19 obj.repo = shorthand[2]
20 obj.branch = shorthand[3] || 'master'
21 obj.host = 'github.com'
22 } else if (mediumhand) {
23 obj.user = mediumhand[1]
24 obj.repo = mediumhand[2]
25 obj.branch = mediumhand[3] || 'master'
26 obj.host = 'github.com'
27 } else if (antiquated) {
28 obj.user = antiquated[1]
29 obj.repo = antiquated[2].replace(/\.git$/i, '')
30 obj.branch = 'master'
31 obj.host = 'github.com'
32 } else {
33 // Turn git+http URLs into http URLs
34 repoUrl = repoUrl.replace(/^git\+/, '')
35
36 if (!isUrl(repoUrl)) return null
37 var parsedURL = url.parse(repoUrl)
38
39 if (!parsedURL.hostname) return null
40 if (parsedURL.hostname !== 'github.com' && !opts.enterprise) return null
41
42 var parts = parsedURL.pathname.match(/^\/([\w-_]+)\/([\w-_\.]+)(\/tree\/[\w-_\.\/]+)?(\/blob\/[\w-_\.\/]+)?/)
43 // ([\w-_\.]+)
44 if (!parts) return null
45 obj.user = parts[1]
46 obj.repo = parts[2].replace(/\.git$/i, '')
47
48 obj.host = parsedURL.hostname || 'github.com'
49
50 if (parts[3]) {
51 obj.branch = parts[3].replace(/^\/tree\//, '').match(/[\w-_.]+\/{0,1}[\w-_]+/)[0]
52 } else if (parts[4]) {
53 obj.branch = parts[4].replace(/^\/blob\//, '').match(/[\w-_.]+\/{0,1}[\w-_]+/)[0]
54 } else {
55 obj.branch = 'master'
56 }
57 }
58
59 if (obj.host === 'github.com') {
60 obj.apiHost = 'api.github.com'
61 } else {
62 obj.apiHost = util.format('%s/api/v3', obj.host)
63 }
64
65 obj.tarball_url = util.format('https://%s/repos/%s/%s/tarball/%s', obj.apiHost, obj.user, obj.repo, obj.branch)
66 obj.clone_url = util.format('https://%s/%s/%s', obj.host, obj.user, obj.repo)
67
68 if (obj.branch === 'master') {
69 obj.https_url = util.format('https://%s/%s/%s', obj.host, obj.user, obj.repo)
70 obj.travis_url = util.format('https://travis-ci.org/%s/%s', obj.user, obj.repo)
71 obj.zip_url = util.format('https://%s/%s/%s/archive/master.zip', obj.host, obj.user, obj.repo)
72 } else {
73 obj.https_url = util.format('https://%s/%s/%s/blob/%s', obj.host, obj.user, obj.repo, obj.branch)
74 obj.travis_url = util.format('https://travis-ci.org/%s/%s?branch=%s', obj.user, obj.repo, obj.branch)
75 obj.zip_url = util.format('https://%s/%s/%s/archive/%s.zip', obj.host, obj.user, obj.repo, obj.branch)
76 }
77
78 obj.api_url = util.format('https://%s/repos/%s/%s', obj.apiHost, obj.user, obj.repo)
79
80 return obj
81}