11cb0ef41Sopenharmony_ciconst { URL } = require('url')
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst PackageUrlCmd = require('../package-url-cmd.js')
41cb0ef41Sopenharmony_ciclass Repo extends PackageUrlCmd {
51cb0ef41Sopenharmony_ci  static description = 'Open package repository page in the browser'
61cb0ef41Sopenharmony_ci  static name = 'repo'
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_ci  getUrl (spec, mani) {
91cb0ef41Sopenharmony_ci    const r = mani.repository
101cb0ef41Sopenharmony_ci    const rurl = !r ? null
111cb0ef41Sopenharmony_ci      : typeof r === 'string' ? r
121cb0ef41Sopenharmony_ci      : typeof r === 'object' && typeof r.url === 'string' ? r.url
131cb0ef41Sopenharmony_ci      : null
141cb0ef41Sopenharmony_ci
151cb0ef41Sopenharmony_ci    if (!rurl) {
161cb0ef41Sopenharmony_ci      throw Object.assign(new Error('no repository'), {
171cb0ef41Sopenharmony_ci        pkgid: spec,
181cb0ef41Sopenharmony_ci      })
191cb0ef41Sopenharmony_ci    }
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_ci    const info = this.hostedFromMani(mani)
221cb0ef41Sopenharmony_ci    const url = info ?
231cb0ef41Sopenharmony_ci      info.browse(mani.repository.directory) : unknownHostedUrl(rurl)
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ci    if (!url) {
261cb0ef41Sopenharmony_ci      throw Object.assign(new Error('no repository: could not get url'), {
271cb0ef41Sopenharmony_ci        pkgid: spec,
281cb0ef41Sopenharmony_ci      })
291cb0ef41Sopenharmony_ci    }
301cb0ef41Sopenharmony_ci    return url
311cb0ef41Sopenharmony_ci  }
321cb0ef41Sopenharmony_ci}
331cb0ef41Sopenharmony_cimodule.exports = Repo
341cb0ef41Sopenharmony_ci
351cb0ef41Sopenharmony_ciconst unknownHostedUrl = url => {
361cb0ef41Sopenharmony_ci  try {
371cb0ef41Sopenharmony_ci    const {
381cb0ef41Sopenharmony_ci      protocol,
391cb0ef41Sopenharmony_ci      hostname,
401cb0ef41Sopenharmony_ci      pathname,
411cb0ef41Sopenharmony_ci    } = new URL(url)
421cb0ef41Sopenharmony_ci
431cb0ef41Sopenharmony_ci    /* istanbul ignore next - URL ctor should prevent this */
441cb0ef41Sopenharmony_ci    if (!protocol || !hostname) {
451cb0ef41Sopenharmony_ci      return null
461cb0ef41Sopenharmony_ci    }
471cb0ef41Sopenharmony_ci
481cb0ef41Sopenharmony_ci    const proto = /(git\+)http:$/.test(protocol) ? 'http:' : 'https:'
491cb0ef41Sopenharmony_ci    const path = pathname.replace(/\.git$/, '')
501cb0ef41Sopenharmony_ci    return `${proto}//${hostname}${path}`
511cb0ef41Sopenharmony_ci  } catch (e) {
521cb0ef41Sopenharmony_ci    return null
531cb0ef41Sopenharmony_ci  }
541cb0ef41Sopenharmony_ci}
55