sherry-utils
Version:
sherry-utils for Sherry
95 lines (80 loc) • 2.25 kB
JavaScript
const GitUrlParse = require('git-url-parse')
const isGitUrl = require('./isGitUrl')
class GitRepoUrl {
constructor(parsed, opts) {
this.opts = opts
this.parsed = parsed
}
get protocol() {
return this.opts.protocol || this.parsed.protocol
}
get gitOrigin() {
return this.parsed.resource || this.opts.gitOrigin
}
get type() {
const match = this.gitOrigin.match(/github|gitlab|bitbucket/)
if (!match) {
throw new Error(`Unknown repo type.`)
}
return match[0]
}
get checkout() {
return this.parsed.hash || 'master'
}
get downloadUrl() {
if (this.protocol === 'ssh') {
return ensureEndingGit(GitUrlParse.stringify(this.parsed, 'ssh'))
} else if (this.protocol.startsWith('http')) {
let url = GitUrlParse
.stringify(this.parsed, this.opts.protocol)
.replace(/\.git$/, '')
if (this.type === 'github') {
url += '/archive/' + this.checkout + '.zip'
} else if (this.type === 'gitlab') {
url += '/repository/archive.zip?ref=' + this.checkout
} else if (this.type === 'bitbucket') {
url += '/get/' + this.checkout + '.zip'
}
return url
}
}
}
function ensureEndingGit(src) {
return src.endsWith('.git') ? src : `${src}.git`
}
function removeLeadingSlash(src) {
return src.startsWith('/')
? src.slice(1)
: src
}
class GitUrlParser {
constructor(opts = {}) {
this.opts = Object.assign({
gitOrigin: 'github.com',
protocol: 'http'
}, opts)
}
setOptions(opts = {}) {
Object.keys(opts).forEach(key => {
if (this.opts[key] && opts[key] !== undefined) {
this.opts[key] = opts[key]
}
})
return this
}
parse(src) {
const { gitOrigin /* i.e. resource */, protocol } = this.opts
if (!isGitUrl(src)) {
if (protocol.startsWith('http')) {
src = `${gitOrigin.startsWith('http')
? gitOrigin
: `${protocol}://${gitOrigin}`
}/${removeLeadingSlash(src)}`
} else if (protocol === 'ssh') {
src = `git@${gitOrigin}:${removeLeadingSlash(src)}.git`
}
}
return new GitRepoUrl(GitUrlParse(src), this.opts)
}
}
module.exports = opts => new GitUrlParser(opts)