1 | const url = require('url')
|
2 | const fetch = require('node-fetch')
|
3 | const { safeJoin } = require('safe-join')
|
4 |
|
5 |
|
6 | const GITHUB = Symbol('GITHUB')
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | async function readRepoURL(_url) {
|
15 |
|
16 |
|
17 | const URL = url.parse(_url)
|
18 | const repoHost = validateRepoURL(_url)
|
19 | if (repoHost !== GITHUB) throw new Error('only github repos are supported for now')
|
20 | const [owner_and_repo, contents_path] = parseRepoURL(repoHost, URL)
|
21 | const folderContents = await getRepoURLContents(repoHost, owner_and_repo, contents_path)
|
22 | return folderContents
|
23 | }
|
24 |
|
25 | async function getRepoURLContents(repoHost, owner_and_repo, contents_path) {
|
26 |
|
27 | if (repoHost === GITHUB) {
|
28 |
|
29 | const APIURL = safeJoin('https://api.github.com/repos', owner_and_repo, 'contents', contents_path)
|
30 | return fetch(APIURL)
|
31 | .then(x => x.json())
|
32 | .catch(
|
33 | error => console.error('Error occurred while fetching ', APIURL, error)
|
34 | )
|
35 | }
|
36 | throw new Error('unsupported host ', repoHost)
|
37 | }
|
38 |
|
39 | function validateRepoURL(_url) {
|
40 |
|
41 |
|
42 | const URL = url.parse(_url)
|
43 | if (URL.host !== 'github.com') return null
|
44 |
|
45 | return GITHUB
|
46 | }
|
47 | function parseRepoURL(repoHost, URL) {
|
48 |
|
49 | if (repoHost === GITHUB) {
|
50 |
|
51 | const [owner_and_repo, contents_path] = URL.path.split('/tree/master')
|
52 | return [owner_and_repo, contents_path]
|
53 | }
|
54 | throw new Error('unsupported host ', repoHost)
|
55 | }
|
56 |
|
57 | module.exports = {
|
58 | readRepoURL,
|
59 | validateRepoURL
|
60 | }
|