git-host.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. 'use strict'
  2. const gitHosts = require('./git-host-info.js')
  3. class GitHost {
  4. constructor (type, user, auth, project, committish, defaultRepresentation, opts = {}) {
  5. Object.assign(this, gitHosts[type])
  6. this.type = type
  7. this.user = user
  8. this.auth = auth
  9. this.project = project
  10. this.committish = committish
  11. this.default = defaultRepresentation
  12. this.opts = opts
  13. }
  14. hash () {
  15. return this.committish ? `#${this.committish}` : ''
  16. }
  17. ssh (opts) {
  18. return this._fill(this.sshtemplate, opts)
  19. }
  20. _fill (template, opts) {
  21. if (typeof template === 'function') {
  22. const options = { ...this, ...this.opts, ...opts }
  23. // the path should always be set so we don't end up with 'undefined' in urls
  24. if (!options.path) {
  25. options.path = ''
  26. }
  27. // template functions will insert the leading slash themselves
  28. if (options.path.startsWith('/')) {
  29. options.path = options.path.slice(1)
  30. }
  31. if (options.noCommittish) {
  32. options.committish = null
  33. }
  34. const result = template(options)
  35. return options.noGitPlus && result.startsWith('git+') ? result.slice(4) : result
  36. }
  37. return null
  38. }
  39. sshurl (opts) {
  40. return this._fill(this.sshurltemplate, opts)
  41. }
  42. browse (path, fragment, opts) {
  43. // not a string, treat path as opts
  44. if (typeof path !== 'string') {
  45. return this._fill(this.browsetemplate, path)
  46. }
  47. if (typeof fragment !== 'string') {
  48. opts = fragment
  49. fragment = null
  50. }
  51. return this._fill(this.browsefiletemplate, { ...opts, fragment, path })
  52. }
  53. docs (opts) {
  54. return this._fill(this.docstemplate, opts)
  55. }
  56. bugs (opts) {
  57. return this._fill(this.bugstemplate, opts)
  58. }
  59. https (opts) {
  60. return this._fill(this.httpstemplate, opts)
  61. }
  62. git (opts) {
  63. return this._fill(this.gittemplate, opts)
  64. }
  65. shortcut (opts) {
  66. return this._fill(this.shortcuttemplate, opts)
  67. }
  68. path (opts) {
  69. return this._fill(this.pathtemplate, opts)
  70. }
  71. tarball (opts) {
  72. return this._fill(this.tarballtemplate, { ...opts, noCommittish: false })
  73. }
  74. file (path, opts) {
  75. return this._fill(this.filetemplate, { ...opts, path })
  76. }
  77. getDefaultRepresentation () {
  78. return this.default
  79. }
  80. toString (opts) {
  81. if (this.default && typeof this[this.default] === 'function') {
  82. return this[this.default](opts)
  83. }
  84. return this.sshurl(opts)
  85. }
  86. }
  87. module.exports = GitHost