github-url.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // https://regex101.com/r/fK2rV3/1
  2. const githubReposIdPattern = new RegExp(/^\/([^/]+)\/([^/]+)$/);
  3. export class GitHubUrl {
  4. private _organizationName: string;
  5. private _reposName: string;
  6. private _branchName: string;
  7. get organizationName(): string {
  8. return this._organizationName;
  9. }
  10. get reposName(): string {
  11. return this._reposName;
  12. }
  13. get branchName(): string {
  14. return this._branchName;
  15. }
  16. get archiveUrl(): string {
  17. const ghUrl = new URL(`/${this.organizationName}/${this.reposName}/archive/refs/heads/${this.branchName}.zip`, 'https://github.com');
  18. return ghUrl.toString();
  19. }
  20. constructor(url: string, branchName = 'main') {
  21. let matched;
  22. try {
  23. const ghUrl = new URL(url);
  24. matched = ghUrl.pathname.match(githubReposIdPattern);
  25. if (ghUrl.hostname !== 'github.com' || matched == null) {
  26. throw new Error();
  27. }
  28. }
  29. catch (err) {
  30. throw new Error(`The specified URL is invalid. : url='${url}'`);
  31. }
  32. this._branchName = branchName;
  33. this._organizationName = matched[1];
  34. this._reposName = matched[2];
  35. }
  36. }