github-url.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 sanitizeBranchChars = new RegExp(/[^a-zA-Z0-9_.]+/g);
  6. // https://regex101.com/r/f4wj8q/1
  7. // GitHub will return a zip file with the v removed if the tag or branch name is "v + number"
  8. const checkVersionName = new RegExp(/^v[\d]/g);
  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. if (encodedTagName !== '') {
  30. const ghUrl = new URL(`/${this.organizationName}/${this.reposName}/archive/refs/tags/${encodedTagName}.zip`, 'https://github.com');
  31. return ghUrl.toString();
  32. }
  33. const ghUrl = new URL(`/${this.organizationName}/${this.reposName}/archive/refs/heads/${encodedBranchName}.zip`, 'https://github.com');
  34. return ghUrl.toString();
  35. }
  36. get extractedArchiveDirName(): string {
  37. if (this._tagName !== '') {
  38. const tagName = this._tagName?.match(checkVersionName) ? this._tagName.replace('v', '') : this._tagName;
  39. return tagName.replaceAll(sanitizeBranchChars, '-');
  40. }
  41. const branchName = this._branchName?.match(checkVersionName) ? this._branchName.replace('v', '') : this._branchName;
  42. return branchName.replaceAll(sanitizeBranchChars, '-');
  43. }
  44. constructor(url: string, branchName = 'main', tagName = '') {
  45. let matched;
  46. try {
  47. const ghUrl = new URL(url);
  48. matched = ghUrl.pathname.match(githubReposIdPattern);
  49. if (ghUrl.hostname !== 'github.com' || matched == null) {
  50. throw new Error();
  51. }
  52. }
  53. catch (err) {
  54. throw new Error(`The specified URL is invalid. : url='${url}'`);
  55. }
  56. this._branchName = branchName;
  57. this._tagName = tagName;
  58. this._organizationName = sanitize(matched[1]);
  59. this._reposName = sanitize(matched[2]);
  60. }
  61. }