github-url.ts 1.2 KB

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