github-url.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import sanitize from 'sanitize-filename';
  2. // https://regex101.com/r/fK2rV3/1
  3. const githubReposIdPattern = new RegExp(/^\/([^/]+)\/([^/]+)$/);
  4. // https://regex101.com/r/CQjSuz/1
  5. const sanitizeSymbolsChars = new RegExp(/[^a-zA-Z0-9_.]+/g);
  6. // https://regex101.com/r/ARgXvb/1
  7. // GitHub will return a zip file with the v removed if the tag or branch name is "v + number"
  8. const sanitizeVersionChars = new RegExp(/^v[\d]/gi);
  9. export class GitHubUrl {
  10. private _organizationName: string;
  11. private _reposName: string;
  12. private _branchName: string;
  13. private _tagName: string;
  14. get organizationName(): string {
  15. return this._organizationName;
  16. }
  17. get reposName(): string {
  18. return this._reposName;
  19. }
  20. get branchName(): string {
  21. return this._branchName;
  22. }
  23. get tagName(): string {
  24. return this._tagName;
  25. }
  26. get archiveUrl(): string {
  27. const encodedBranchName = encodeURIComponent(this.branchName);
  28. const encodedTagName = encodeURIComponent(this.tagName);
  29. const zipUrl = encodedTagName !== '' ? `tags/${encodedTagName}` : `heads/${encodedBranchName}`;
  30. const ghUrl = new URL(`/${this.organizationName}/${this.reposName}/archive/refs/${zipUrl}.zip`, 'https://github.com');
  31. return ghUrl.toString();
  32. }
  33. get extractedArchiveDirName(): string {
  34. const name = this._tagName !== '' ? this._tagName : this._branchName;
  35. return name.replace(sanitizeVersionChars, m => m.substring(1)).replaceAll(sanitizeSymbolsChars, '-');
  36. }
  37. constructor(url: string, branchName = 'main', tagName = '') {
  38. let matched;
  39. try {
  40. const ghUrl = new URL(url);
  41. matched = ghUrl.pathname.match(githubReposIdPattern);
  42. if (ghUrl.hostname !== 'github.com' || matched == null) {
  43. throw new Error();
  44. }
  45. }
  46. catch (err) {
  47. throw new Error(`The specified URL is invalid. : url='${url}'`);
  48. }
  49. this._branchName = branchName;
  50. this._tagName = tagName;
  51. this._organizationName = sanitize(matched[1]);
  52. this._reposName = sanitize(matched[2]);
  53. }
  54. }