• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1const { URL } = require('url')
2
3const PackageUrlCmd = require('../package-url-cmd.js')
4class Repo extends PackageUrlCmd {
5  static description = 'Open package repository page in the browser'
6  static name = 'repo'
7
8  getUrl (spec, mani) {
9    const r = mani.repository
10    const rurl = !r ? null
11      : typeof r === 'string' ? r
12      : typeof r === 'object' && typeof r.url === 'string' ? r.url
13      : null
14
15    if (!rurl) {
16      throw Object.assign(new Error('no repository'), {
17        pkgid: spec,
18      })
19    }
20
21    const info = this.hostedFromMani(mani)
22    const url = info ?
23      info.browse(mani.repository.directory) : unknownHostedUrl(rurl)
24
25    if (!url) {
26      throw Object.assign(new Error('no repository: could not get url'), {
27        pkgid: spec,
28      })
29    }
30    return url
31  }
32}
33module.exports = Repo
34
35const unknownHostedUrl = url => {
36  try {
37    const {
38      protocol,
39      hostname,
40      pathname,
41    } = new URL(url)
42
43    /* istanbul ignore next - URL ctor should prevent this */
44    if (!protocol || !hostname) {
45      return null
46    }
47
48    const proto = /(git\+)http:$/.test(protocol) ? 'http:' : 'https:'
49    const path = pathname.replace(/\.git$/, '')
50    return `${proto}//${hostname}${path}`
51  } catch (e) {
52    return null
53  }
54}
55