url-helper.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. const user = settings.sshUser.length > 0 ? settings.sshUser : 'git'
  15. return `${user}@${serviceUrl.hostname}:${encodedOwner}/${encodedName}.git`
  16. }
  17. // "origin" is SCHEME://HOSTNAME[:PORT]
  18. return `${serviceUrl.origin}/${encodedOwner}/${encodedName}`
  19. }
  20. export function getServerUrl(url?: string): URL {
  21. let resolvedUrl = process.env['GITHUB_SERVER_URL'] || 'https://github.com'
  22. if (hasContent(url, WhitespaceMode.Trim)) {
  23. resolvedUrl = url!
  24. }
  25. return new URL(resolvedUrl)
  26. }
  27. export function getServerApiUrl(url?: string): string {
  28. if (hasContent(url, WhitespaceMode.Trim)) {
  29. let serverUrl = getServerUrl(url)
  30. if (isGhes(url)) {
  31. serverUrl.pathname = 'api/v3'
  32. } else {
  33. serverUrl.hostname = 'api.' + serverUrl.hostname
  34. }
  35. return pruneSuffix(serverUrl.toString(), '/')
  36. }
  37. return process.env['GITHUB_API_URL'] || 'https://api.github.com'
  38. }
  39. export function isGhes(url?: string): boolean {
  40. const ghUrl = new URL(
  41. url || process.env['GITHUB_SERVER_URL'] || 'https://github.com'
  42. )
  43. const hostname = ghUrl.hostname.trimEnd().toUpperCase()
  44. const isGitHubHost = hostname === 'GITHUB.COM'
  45. const isGitHubEnterpriseCloudHost = hostname.endsWith('.GHE.COM')
  46. const isLocalHost = hostname.endsWith('.LOCALHOST')
  47. return !isGitHubHost && !isGitHubEnterpriseCloudHost && !isLocalHost
  48. }
  49. function pruneSuffix(text: string, suffix: string) {
  50. if (hasContent(suffix, WhitespaceMode.Preserve) && text?.endsWith(suffix)) {
  51. return text.substring(0, text.length - suffix.length)
  52. }
  53. return text
  54. }
  55. enum WhitespaceMode {
  56. Trim,
  57. Preserve
  58. }
  59. function hasContent(
  60. text: string | undefined,
  61. whitespaceMode: WhitespaceMode
  62. ): boolean {
  63. let refinedText = text ?? ''
  64. if (whitespaceMode == WhitespaceMode.Trim) {
  65. refinedText = refinedText.trim()
  66. }
  67. return refinedText.length > 0
  68. }