url-helper.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import * as assert from 'assert'
  2. import {URL} from 'url'
  3. import {IGitSourceSettings} from './git-source-settings'
  4. export function getFetchUrl(settings: IGitSourceSettings): string {
  5. assert.ok(
  6. settings.repositoryOwner,
  7. 'settings.repositoryOwner must be defined'
  8. )
  9. assert.ok(settings.repositoryName, 'settings.repositoryName must be defined')
  10. const serviceUrl = getServerUrl(settings.githubServerUrl)
  11. const encodedOwner = encodeURIComponent(settings.repositoryOwner)
  12. const encodedName = encodeURIComponent(settings.repositoryName)
  13. if (settings.sshKey) {
  14. return `git@${serviceUrl.hostname}:${encodedOwner}/${encodedName}.git`
  15. }
  16. // "origin" is SCHEME://HOSTNAME[:PORT]
  17. return `${serviceUrl.origin}/${encodedOwner}/${encodedName}`
  18. }
  19. export function getServerUrl(url?: string): URL {
  20. let urlValue =
  21. url && url.trim().length > 0
  22. ? url
  23. : process.env['GITHUB_SERVER_URL'] || 'https://github.com'
  24. return new URL(urlValue)
  25. }
  26. export function getServerApiUrl(url?: string): string {
  27. let apiUrl = 'https://api.github.com'
  28. if (isGhes(url)) {
  29. const serverUrl = getServerUrl(url)
  30. apiUrl = new URL(`${serverUrl.origin}/api/v3`).toString()
  31. }
  32. return apiUrl
  33. }
  34. export function isGhes(url?: string): boolean {
  35. const ghUrl = getServerUrl(url)
  36. return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'
  37. }