This repository was archived by the owner on Sep 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathread-repo-url.js
66 lines (61 loc) · 2.08 KB
/
read-repo-url.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const url = require("url");
const fetch = require("node-fetch");
const { safeJoin } = require("safe-join");
// supported repo host types
const GITHUB = Symbol("GITHUB");
// const BITBUCKET = Symbol('BITBUCKET')
// const GITLAB = Symbol('GITLAB')
/**
* Takes a url like https://github.com/netlify-labs/all-the-functions/tree/master/functions/9-using-middleware
* and returns https://api.github.com/repos/netlify-labs/all-the-functions/contents/functions/9-using-middleware
*/
async function readRepoURL(_url) {
const URL = url.parse(_url);
const repoHost = validateRepoURL(_url);
if (repoHost !== GITHUB)
throw new Error("only github repos are supported for now");
const [owner_and_repo, contents_path] = parseRepoURL(repoHost, URL);
const folderContents = await getRepoURLContents(
repoHost,
owner_and_repo,
contents_path
);
return folderContents;
}
async function getRepoURLContents(repoHost, owner_and_repo, contents_path) {
// naive joining strategy for now
if (repoHost === GITHUB) {
// https://developer.github.com/v3/repos/contents/#get-contents
const APIURL = safeJoin(
"https://api.github.com/repos",
owner_and_repo,
"contents",
contents_path
);
return fetch(APIURL)
.then(x => x.json())
.catch(
error => console.error("Error occurred while fetching ", APIURL, error) // eslint-disable-line no-console
);
}
throw new Error("unsupported host ", repoHost);
}
function validateRepoURL(_url) {
const URL = url.parse(_url);
if (URL.host !== "github.com") return null;
// other validation logic here
return GITHUB;
}
function parseRepoURL(repoHost, URL) {
// naive splitting strategy for now
if (repoHost === GITHUB) {
// https://developer.github.com/v3/repos/contents/#get-contents
const [owner_and_repo, contents_path] = URL.path.split("/tree/master"); // what if it's not master? note that our contents retrieval may assume it is master
return [owner_and_repo, contents_path];
}
throw new Error("unsupported host ", repoHost);
}
module.exports = {
readRepoURL,
validateRepoURL
};