repo.js 1.2 KB

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